首页 > 解决方案 > 如何使一个字典中的值成为 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},

     }

对于最初的错误格式和对我想要得到的内容的疯狂描述真的很抱歉。我只需要简单描述一下如何让这些值成为第二个字典的键。我希望这更清楚一些!

标签: pythondictionary

解决方案


假设您的数据顺序与您的问题一样,您可以执行以下操作:

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

推荐阅读