python - 用列表作为值反转字典(不能作为键重复)
问题描述
我目前正在处理初学者的任务(在 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 特定知识
谢谢!
解决方案
您的构造问题是密钥重复,这在字典中是不允许的。您的代码中也没有关于列表(对于值)的任何内容。
方法是使用 a defaultdict
, with list
as 值。如果键不存在,它会放置一个空列表,然后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]}
推荐阅读
- ruby-on-rails - 过滤路由参数
- python - 如何在循环中获取当前日期时间
- node.js - Google 服务帐号:API 返回错误:TypeError: source.hasOwnProperty is not a function after a hour
- javascript - 如何在不使用数据库的情况下保存分数(使用 javascript 的 gambit 游戏)
- python - pptx-python 不需要的图表标题
- python - 使用pickle保存和重用TfidfVectorizer会引发错误
- asp.net - Dotless 无法加载文件或程序集 dotless.aspnet
- r - 如何将 R 中的 2 个具有相同日期范围的表合并并计算相关性?
- node.js - 发布时,我可以将“link:../dir”替换为所链接的包的版本吗?
- python - Python多进程记录到共享文件