【问题标题】:Python 3: How Do I Invert A Dictionary That Has A List As A ValuePython 3:如何反转具有列表作为值的字典
【发布时间】: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


    【解决方案1】:

    您可以使用defaultdict 删除 else 语句并检查密钥是否存在。如果不存在,则会创建一个空列表。

    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 循环。

    【讨论】:

    • 谢谢,非常感谢。现在我只需要对它进行逆向工程,这样我就可以记住它。
    【解决方案2】:

    你可以替换你的 if else :

    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
    

    但是我找不到跳过一个的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 2017-04-11
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多