这种字典理解是否可行?

时间:2017-09-01 20:02:56

标签: python dictionary dictionary-comprehension

我试图创建一个字典理解的字典。 字典应如下所示:

到目前为止,我试过了:

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']}

但这会返回一个dict,其中所有玩家都拥有最后一个玩家的Items,我也发现这来自for player_object in player_objects。 我可以通过词典理解得到我想要的词典吗?

1 个答案:

答案 0 :(得分:1)

虽然可能有更多的Pythonic解决方案,但我确实修复了原始代码。问题是LEFT OUTER JOIN "object2" T3 ON ( "object1"."id" = T3."object1_id" and "object2"."status" = fail)理解中的for加倍dict。执行此操作时,您可以单独迭代player_objectsextended_data。相反,迭代其中一个并使用这些名称访问另一个dict。你也不能在理解中使用self - 它不会引用任何东西,除非你的代码恰好生活在一个类方法中。

这是一个模型:

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']}