【发布时间】:2021-03-15 11:42:58
【问题描述】:
所以对于类,我需要使用一个包含列表作为值的字典并将其反转。我找到了几种方法来做到这一点,但问题是当存在非唯一值时。我找到了一种方法来做到这一点,但我觉得必须有更简单和简化的方法来做到这一点。
summon_locations = {
"Solaire": ['Gargoyles' ,'Gaping Dragon', "Ornstein/Smough"],
"Gotthard": ['Abyss Watchers' ,'Pontiff Sulyvahn', "Grand Archives"],
"Lucatiel": ['Lost Sinner', 'Smelter Demon', 'The Rotten'],
}
#Original dictionary
summon_locations = {
"Solaire": ['Gargoyles' ,'Gaping Dragon', "Ornstein/Smough"],
"Gotthard": ['Abyss Watchers' ,'Pontiff Sulyvahn', "Grand Archives"],
"Lucatiel": ['Lost Sinner', 'Smelter Demon', 'Abyss Watchers'],
}
#Dictionary with a non-unique value
def invert(d):
big_dict = {}
for k, v in d.items():
for i in v:
if i not in big_dict:
big_dict[i] = [k]
else:
big_dict[i].append(k)
return big_dict
print(invert(summon_locations))
输出原件:
{'Gargoyles':['Solaire'],'Gaping Dragon':['Solaire'],'Ornstein/Smough':['Solaire'],'Abyss Watchers':['Gotthard'],'Pontiff Sulyvahn':['Gotthard'],'Grand Archives':['Gotthard'],'Lost Sinner':['Lucatiel'],'Smelter Demon':['Lucatiel'],'The Rotten':['Lucatiel ']}
输出一个非唯一值:
{'Gargoyles': ['Solaire'], 'Gaping Dragon': ['Solaire'], 'Ornstein/Smough': ['Solaire'], '深渊守望者': ['Gotthard', 'Lucatiel' ], 'Pontiff Sulyvahn': ['Gotthard'], '大档案馆': ['Gotthard'], '失落的罪人': ['Lucatiel'], '冶炼恶魔': ['Lucatiel']}
因此它只会获取重复值的原始键并将其附加到列表中。我已经看到了一些很酷的方法来反转字典,但是由于列表,它们在这里往往会失败。
【问题讨论】:
标签: python-3.x list dictionary