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?
Although there's probably a more Pythonic solution, I do have a fix for your original code. The problem is the double
for
in yourdict
comprehension. When you do that you iterate over bothplayer_objects
andextended_data
independently. Instead, iterate over one of them and use those names to access the otherdict
. You also can't useself
in that comprehension - it doesn't refer to anything, unless your code happens to be living in a class method.Here's a mockup: