首页 > 解决方案 > 用列表作为值反转字典(不能作为键重复)

问题描述

我目前正在处理初学者的任务(在 Python 中):“反转字典:键变为值,值变为键。原始值是列表,当转换为键时,不得重复!”

首先,我必须写下我已经看到了几个(类似的)问题,但没有一个适用于我的任务。

其次,我尝试使用嵌套的 for 和 if 循环编写解决方案 - 未成功。

然后,我在应用互联网解决方案后编写了这段代码:

def invert(dict1):
  invertedDict1 = dict()
  
  invertedDict1 = {value: key for key in dict1 for value in dict1[key]}
      
  #print(dict1)
  print(invertedDict1)    
  
dict1 = {1: [2, 3, 5],
         2: [1, 4],
         3: [1, 2],
         }

invert(dict1)

输出:

{2: 3, 3: 1, 5: 1, 1: 3, 4: 2}

它应该是:

{1:[2,3], 2:[1,3], 3:[1], 4:[2], 5:[1]}

有人知道我在哪里犯了错误(或错误)吗?

PS 我是 Python 的新手,来自 C/C++ 背景,所以请理解我缺乏 Python 特定知识

谢谢!

标签: pythonlistdictionary

解决方案


您的构造问题是密钥重复,这在字典中是不允许的。您的代码中也没有关于列表(对于值)的任何内容。

方法是使用 a defaultdict, with listas 值。如果键不存在,它会放置一个空列表,然后key在其中附加 。

from collections import defaultdict

def invert(dict1):
    invertedDict1 = defaultdict(list)
    for key, values in dict1.items():
        for value in values:
            invertedDict1[value].append(key)
    return invertedDict1


dict1 = {1: [2, 3, 5], 2: [1, 4], 3: [1, 2], }
print(invert(dict1))  # {2: [1, 3], 3: [1], 5: [1], 1: [2, 3], 4: [2]}

推荐阅读