【问题标题】:inversing a dictionary in python with duplicate values在python中用重复值反转字典
【发布时间】:2021-01-24 22:08:03
【问题描述】:

我需要反转一个字典,这样每个旧值现在都将成为一个键,而旧键将成为新值。

诀窍是旧字典中可能有多个相同的值,所以我需要新字典中的每个值都是一个列表,如果旧字典中有相同的值,那么它们都将在新字典的值列表。

例如: 字典 {"python" : 1, "is" : 1, "cool" : 2}

最终会变成:{1 : ["python", "is"], 2 : ["cool"]}

这是我尝试过的:

def inverse_dict(my_dict):
    new_dict = {}
    values_list = list(my_dict.values())
    new_dict = new_dict.fromkeys(values_list)
    for key in new_dict:
        new_dict[key] = []
    for old_key in my_dict:
        new_dict[my_dict[old_key]] = list(new_dict[my_dict[old_key]]).append(old_key)
    return new_dict

非常感谢对我的方法(以及解决问题的更好方法)的任何帮助,因为我对 Python 非常陌生,谢谢!

【问题讨论】:

标签: python dictionary


【解决方案1】:

您可以使用dict.setdefault检查字典中是否存在键,如果不存在,则创建新值(在这种情况下为空列表[]):

d =  {"python" : 1, "is" : 1, "cool" : 2}

reversed_d = {}
for k, v in d.items():
    reversed_d.setdefault(v, []).append(k)

print(reversed_d)

打印:

{1: ['python', 'is'], 2: ['cool']}

这可以更明确地改写为:

d =  {"python" : 1, "is" : 1, "cool" : 2}

reversed_d = {}
for k, v in d.items():
    if v not in reversed_d:
        reversed_d[v] = [k]
    else:
        reversed_d[v].append(k)

print(reversed_d)

【讨论】:

    【解决方案2】:

    您可以使用defaultdict 来避免预填充步骤

    from collections import defaultdict
    
    def inverse_dict(my_dict: dict):
        new_dict = defaultdict(list)
        for k, v in my_dict.items():
            new_dict[v].append(k)
        return new_dict
    

    【讨论】:

      【解决方案3】:

      虽然我更喜欢使用默认字典的@azro's answer,但另一种解决方案是使用字典和列表推导。

      看起来像这样:

      {value : [key for key in my_dict if my_dict[key] == value] for value in set(my_dict.values())}
      

      它的作用是遍历字典的值而不重复 - set(my_dict.values())

      它将每个值构建为一个键(因为它位于“:”的左侧)。

      它的值是指向该值的键列表 - [key for key in my_dict if my_dict[key] == value]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        • 2021-08-21
        • 2017-09-12
        • 1970-01-01
        • 1970-01-01
        • 2023-01-21
        相关资源
        最近更新 更多