将列表作为值(不能作为键重复)反转字典

2024-10-04 11:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在从事一项初学者任务(Python): 反转字典:键变为值,值变为键。原始值是列表,当转换为键时,不能重复

首先,我必须写下,我见过几个(类似的)问题,但没有一个适用于我的任务

其次,我尝试使用嵌套for和if循环编写解决方案,但没有成功

然后,在应用internet解决方案后,我编写了以下代码:

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]}

有人知道我在哪里犯的错误吗

附言。 我是Python的新手,来自C/C++背景,因此请理解我对Python特定知识的缺乏

谢谢


Tags: key代码in列表forif字典value
3条回答

您可以使用defaultdict轻松地完成此操作:

from collections import defaultdict

d = defaultdict(list)

for k, v in dict1.items():
    for x in v:
        d[x].append(k)

print(d)
defaultdict(list, {2: [1, 3], 3: [1], 5: [1], 1: [2, 3], 4: [2]})

defaultdict(list)在访问键时总是返回一个list:一个新的空列表[]如果这是第一次访问d[x],那么与x关联的现有值列表[k1, k2, ...]如果以前访问过d[x]

这样,您可以在列表中存储与x关联的所有键k

构造的问题是关键字重复,这在dict中是不允许的。此外,代码中没有关于列表(值)的任何内容

方法是使用^{},以list作为值。如果键不存在,它将放置一个空列表,然后在其中附加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]}

azro's answer非常好,但是如果有帮助的话,我只想添加一个没有collections的实现。如果需要,我将使用^{}插入一个新列表,否则将获取现有列表

def invert(d):
    inverted = {}
    for k, v in d.items():
        for x in v:
            L = inverted.setdefault(x, [])
            L.append(k)
    return inverted

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]}

带有setdefault的这一行表示:

if x not in inverted:
    inverted[x] = []
L = inverted[x]

相关问题 更多 >