我目前正在从事一项初学者任务(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特定知识的缺乏
谢谢
您可以使用
defaultdict
轻松地完成此操作:defaultdict(list)
在访问键时总是返回一个list
:一个新的空列表[]
如果这是第一次访问d[x]
,那么与x
关联的现有值列表[k1, k2, ...]
如果以前访问过d[x]
这样,您可以在列表中存储与
x
关联的所有键k
构造的问题是关键字重复,这在dict中是不允许的。此外,代码中没有关于列表(值)的任何内容
方法是使用^{} ,以
list
作为值。如果键不存在,它将放置一个空列表,然后在其中附加key
azro's answer非常好,但是如果有帮助的话,我只想添加一个没有} 插入一个新列表,否则将获取现有列表
collections
的实现。如果需要,我将使用^{带有
setdefault
的这一行表示:相关问题 更多 >
编程相关推荐