python - 如何使一个字典中的值成为 python 中新字典的键?
问题描述
所以说我有一本字典
dict{int: tuple(int, str)}
我想制作一个格式的新字典
dict{str: dict{int: int}}
所以这是我想要得到的一个例子:
d1 = {
1: (22, 'this is a phrase'),
2: (333, 'here is a sentence')
}
并通过一个函数,我需要能够操纵第一本字典来获得第二本:
d2 = {
'this is a phrase': {1: 22},
'here is a sentence': {2: 333},
}
对于最初的错误格式和对我想要得到的内容的疯狂描述真的很抱歉。我只需要简单描述一下如何让这些值成为第二个字典的键。我希望这更清楚一些!
解决方案
假设您的数据顺序与您的问题一样,您可以执行以下操作:
d1 = {
1: (22, 'this is a phrase',['apple', 'grape']),
2: (333, 'here is a sentence',['grape', 'cherry'])
}
d2 = {}
for key, values in d1.items():
for food in values[-1]:
if food not in d2:
d2[food] = {}
d2[food][values[0]] = [values[1]]
print d2
# Output: {'cherry': {333: ['here is a sentence']}, 'grape': {333: ['here is a sentence'], 22: ['this is a phrase']}, 'apple': {22: ['this is a phrase']}}
推荐阅读
- http - 如何在 web API 的颤动中发出 POST 请求
- c++ - 使用 wndproc 作为类的成员函数
- git - 解决 git 中的冲突
- rest - 如何将类作为参数传递给 Web Api
- c# - 从 Excel 加载 DataTable:无法将“System.DateTime”类型的对象转换为“System.String”类型
- java - 我收到以下错误,我正在使用 Android Studio 3.1
- javascript - 当从 HTML 页面而不是 .js 文件调用函数时,AngularJS $scope 未定义
- sorting - gwt 单元格表动态列 - 排序需要一个例子
- java - 如何在不指定列名的情况下使用 jdbcTemplate 更新整个对象?
- javascript - 如何在 html 中嵌入 SVG