Python Forum
how to assign items from a list to a dictionary
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to assign items from a list to a dictionary
#1
How can i simplify this code?

listplayers = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
dictionary  = {
    'playersname':[]
    'totalwin':[]
    'totalloss':[]
    }

for x in listplayers:
    dictionary['playersname'].append(x[0])
    dictionary['totalwins'].append(x[1])
    dictionary['totalloss'].append(x[2])
i know it seems pretty simplified now but if my dictionary and my x has 40 items, it gets pretty tedious to write
Reply
#2
You dictionary doesn't make any sense. Why have a dictionary of lists? Doesn't a list of dictionaries make more sense, or better yet a dictionary of dictionaries? Here players_dict is a dictionary of players where each player is the player's stats.
players_list = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
players_dict = {player[0]:{"Win":player[1], "Lose":player[2]} for player in players_list}

print(players_list)
print(players_dict)
Output:
[['player1', 5, 1, 300, 100], ['player2', 10, 5, 650, 150], ['player3', 17, 6, 1100, 1050]] {'player1': {'Win': 5, 'Lose': 1}, 'player2': {'Win': 10, 'Lose': 5}, 'player3': {'Win': 17, 'Lose': 6}}
Why do you need to convert data? Why isn't it already in the format you want? Are you doing something like saving program state information in a CSV format file? Organizing information in columns makes sense for some things, but there are better file formats for saving program state (like JSON).

To answer your initial question. You want to transpose the lists to put like items together. Your loop does this just fine, and increasing the number number of players doesn't require a change in the code at all. You can also let python do the looping. Here I collect the zipped lists using a list comprehension. The list comprehension does the looping.
listplayers = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
transposed = [list(i) for i in zip(*listplayers)]  # Group all items by index
dictionary  = {
    'playersname':transposed[0],
    'totalwin':transposed[1],
    'totalloss':transposed[2]
    }

print(dictionary)
Output:
{'playersname': ['player1', 'player2', 'player3'], 'totalwin': [5, 10, 17], 'totalloss': [1, 5, 6]}
Or you can do much the same thing but using function calls instead of a list comprehension to make the lists. Here list() does the looping.
listplayers = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
transposed = list(map(list, zip(*listplayers)))
dictionary  = {
    'playersname':transposed[0],
    'totalwin':transposed[1],
    'totalloss':transposed[2]
    }

print(dictionary)
Output is the same.

If your player lists contain more information than name, wins and losses, and you are looking for a way to automatically add those extra fieldsfields to your dictionary, there is no easy way to do that. Somewhere you have to do:
dictionary[key]=item
For example, you player arrays each have 5 values. I am going to call item 4 "balance" and item 5 "something". I do the transpose exactly the same way, but have to add more dictionary keys.
listplayers = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
transposed = list(map(list, zip(*listplayers)))
dictionary  = {
    'playersname':transposed[0],
    'totalwin':transposed[1],
    'totalloss':transposed[2],
    'balance':transposed[3],
    'something':transposed[4]
    }
If you have a list of dictionary keys and a list of arrays, you can do a dictionary comprehension..
dictionary = {key:value for key, value in zip(("playersname", "totalwin", "totalloss", "balance", "something"), transposed}
Reply
#3
You should take a look at making a player class.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#4
It is so easy to make a data class, and the syntax to access the fields is better.
from dataclasses import dataclass

@dataclass
class Player:
    wins : int = 0
    losses : int = 0

players_list = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
players = {player[0]: Player(*player[1:3]) for player in players_list}

print(players)
Output:
{'player1': Player(wins=5, losses=1), 'player2': Player(wins=10, losses=5), 'player3': Player(wins=17, losses=6)}
If each player has more information than wins and losses you add these to the dataclass. If each player has 40 attributes the dataclass would have 39 attributes
@dataclass
class Player:
    wins : int = 0
    losses : int = 0
    balance : int = 0  # Extra attributes starting here
    something : int = 0

players_list = [['player1', 5,1,300,100],['player2', 10,5,650,150],['player3', 17,6,1100,1050]]
players = {player[0]: Player(*player[1:]) for player in players_list}

print(players)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 182 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  Dictionary in a list bashage 2 544 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 667 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 488 Oct-27-2023, 03:03 PM
Last Post: buran
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,322 May-22-2023, 10:39 PM
Last Post: ICanIBB
  How to add list to dictionary? Kull_Khan 3 998 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  Finding combinations of list of items (30 or so) LynnS 1 873 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,576 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  How to get list of exactly 10 items? Mark17 1 2,506 May-26-2022, 01:37 PM
Last Post: Mark17
  check if element is in a list in a dictionary value ambrozote 4 1,964 May-11-2022, 06:05 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020