Is this Dictionary comprehension possible?

110 Views Asked by At

Im trying to create a dictionary with a dictionary comprehension. The dict should look like this:

So far I tried:

player_objects = ['list', 'of', 'player_objects']
extended_data = {player_name:{'Money':100, 'Items'=['Item1', 'Item2']}}
data = {player_object:extended_data.get(player).get('Items') for player in extended_data for player_object in player_objects}
#expected output:
data = {player_object:['list', 'of', 'items']}

But this returns a dict where all players have the Items of the last player, I also figured out this comes from for player_object in player_objects. Can I get the dict I want only with dictionary comprehension?

1

There are 1 best solutions below

0
On BEST ANSWER

Although there's probably a more Pythonic solution, I do have a fix for your original code. The problem is the double for in your dict comprehension. When you do that you iterate over both player_objects and extended_data independently. Instead, iterate over one of them and use those names to access the other dict. You also can't use self in that comprehension - it doesn't refer to anything, unless your code happens to be living in a class method.

Here's a mockup:

player_objects = ['player_a', 'player_b', 'player_c']
extended_data = {
    'player_a': {'Money': 100, 'Items': ['dagger', 'armor']},
    'player_b': {'Money': 50, 'Items': ['sword', 'shield']},
    'player_c': {'Money': 20, 'Items': ['boots', 'staff']},
}

items_by_player = {player: extended_data[player].get('Items') for player in player_objects}

print(items_by_player)
# {'player_a': ['dagger', 'armor'], 'player_b': ['sword', 'shield'], 'player_c': ['boots', 'staff']}