您如何从一个字典中获得一个值作为python中新字典的键?

时间:2018-12-07 04:28:00

标签: python dictionary

所以说我有字典

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

     }

对于最初的格式错误以及对我要获取的内容的疯狂描述感到非常抱歉。我只需要关于如何获取值以成为第二个字典的键的简单描述。我希望这更加清楚!

3 个答案:

答案 0 :(得分:1)

假设您的数据顺序与问题相同,那么您可以执行以下操作:

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

答案 1 :(得分:1)

d2 = {}
# we loop through all key: value pairs in the dict
for k, v in d1.items():
    # we unpack the tuple here
    num, newkey = v
    # we then create a new entry for the newkey if it does not exist
    if newkey not in d2:
        d2[newkey] = {}
    d2[newkey][k] = num

这会产生

{'this is a phrase': {1: 22}, 'here is a sentence': {2: 333}}

根据问题中的更改要求进行了编辑。

答案 2 :(得分:0)

遍历d1中的键以获取要反汇编的值。对于每个值,遍历数组value[2]中的项目,并在每个项目下方的{value[0], value[1]}中插入d2。将d1[k1]分配给临时变量可以使其更易于阅读:

d2 = {}
for k1 in d1.keys():
    item = d1[k1]
    for k2 in item[2]:
        if k2 in d2:
          d2[k2].append({item[0]: item[1]})
        else:
          d2[k2] = [{item[0]: item[1]}]

请注意,在尝试追加之前,我们先检查d2中的密钥是否存在;否则,Python会尝试获取d2[k2]并抛出一个 KeyError不存在时k2