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 Scripts
CookBook - Shmup - PyQt5 Music Player


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
  For Word, Count in List (Counts.Items()) new_coder_231013 6 730 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  How to get list of exactly 10 items? Mark17 1 442 May-26-2022, 01:37 PM
Last Post: Mark17
  check if element is in a list in a dictionary value ambrozote 4 746 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 761 Apr-28-2022, 06:59 AM
Last Post: buran
  Reading list items without brackets and quotes jesse68 6 1,527 Jan-14-2022, 07:07 PM
Last Post: jesse68
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 1,164 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
Question How to gather specific second-level items from a list chatguy 2 807 Dec-17-2021, 05:05 PM
Last Post: chatguy
  deleting select items from a list Skaperen 13 2,440 Oct-11-2021, 01:02 AM
Last Post: Skaperen
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,015 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Getting All Items From A List knight2000 4 1,317 Sep-25-2021, 12:56 AM
Last Post: knight2000

Forum Jump:

User Panel Messages

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