因此,对于类,我需要一个字典,其中有一个列表作为一个值,并反演它。我已经找到了几种方法来做到这一点,但问题是什么时候有非独特的价值观。我找到了一种方法来做到这一点,但我觉得必须有更简单和精简的方法来做到这一点。
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))输出原文:
{“守望者”:“哥塔德”、“庞蒂夫·苏莱温”:“哥塔德”、“大档案馆”:“哥塔德”、“大档案馆”、“哥塔德”、“迷失斯内斯特”、“卢卡蒂尔”、“冶炼厂德蒙”、“卢卡蒂尔”、“卢卡蒂尔”、“卢卡蒂尔”。
输出一个非唯一值:
{“守望者”:“哥塔德”、“卢卡蒂尔”、“庞蒂夫·苏莱温”、“哥塔德”、“大档案馆”:“哥塔德”、“迷失斯内尔”、“卢卡蒂尔”、“冶炼厂德蒙”:“卢卡蒂尔”}
因此,它将只获取重复值的原始键,并将其附加到列表中。我已经看到了一些很酷的倒置字典的方法,但是由于列表的原因,它们往往会在这里失败。
发布于 2021-03-15 12:16:21
您可以使用违约删除use语句,并检查密钥是否存在。如果不存在,将创建一个空列表。
from pprint import pprint
summon_locations = {
"Solaire": ['Gargoyles', 'Gaping Dragon', "Ornstein/Smough"],
"Gotthard": ['Abyss Watchers', 'Pontiff Sulyvahn', "Grand Archives"],
"Lucatiel": ['Lost Sinner', 'Smelter Demon', 'Abyss Watchers'],
}
if __name__ == '__main__':
from collections import defaultdict
inverted = defaultdict(list)
for key, values in summon_locations.items():
for value in values:
inverted[value].append(key)
pprint(inverted)输出
defaultdict(<class 'list'>,
{'Abyss Watchers': ['Gotthard', 'Lucatiel'],
'Gaping Dragon': ['Solaire'],
'Gargoyles': ['Solaire'],
'Grand Archives': ['Gotthard'],
'Lost Sinner': ['Lucatiel'],
'Ornstein/Smough': ['Solaire'],
'Pontiff Sulyvahn': ['Gotthard'],
'Smelter Demon': ['Lucatiel']}),这与一行类似。
[inverted[value].append(key) for key, values in summon_locations.items() for value in values]但是,一个行并不总是更好,在这种情况下,我将与两个for循环一起使用。
发布于 2021-03-15 12:05:40
您可以替换您的if:
def invert(d):
big_dict = {}
for k, v in d.items():
for i in v:
big_dict[i] = big_dict.get(i, []) + [k]
return big_dict然而,我却找不到一种方法来跳过。
https://stackoverflow.com/questions/66637332
复制相似问题