将两个词典编成一个

时间:2017-02-06 18:14:28

标签: python dictionary

我有两本词典:

dict1 = {'a': 1,
         'b': 2,
         'c': 3,
         'd': 4,
         'x': 5}

dict2 = {'a': 'start',
         'b': 'start',
         'c': 'end',
         'd': 'end'}

我正在尝试创建一个新的字典,将值startend映射为包含dict1信息的字典的键,同时保留那些不存在的字典在dict2中作为键,例如:

dict3 = {'start': {'a': 1, 'b': 2},
         'end': {'c': 3, 'd': 4},
         'x': {'x': 5}
        }

2 个答案:

答案 0 :(得分:2)

使用dict.setdefault()dict3中创建嵌套词典(如果还没有),并使用dict.get()来确定顶级输出词典中的键:

dict3 = {}
for k, v in dict1.items():
    nested = dict3.setdefault(dict2.get(k, k), {})
    nested[k] = v

因此,dict2.get(k, k)将为来自dict2的给定密钥生成dict1的值,并使用密钥本身作为默认值。因此,对于'x'密钥,由于'x'中没有该密钥的映射,因此生成dict2

演示:

>>> dict3 = {}
>>> for k, v in dict1.items():
...     nested = dict3.setdefault(dict2.get(k, k), {})
...     nested[k] = v
...
>>> dict3
{'start': {'a': 1, 'b': 2}, 'end': {'c': 3, 'd': 4}, 'x': {'x': 5}}

答案 1 :(得分:1)

我实际上是在抽象示例并在这里输入我的问题时想出来的(应该可以在早些时候做到这一点......)。无论如何:耶!

所以这是我的解决方案,万一它可以帮助某人。如果有人知道更快捷或更优雅的方式,我会很高兴学习!

dict3 = dict()

for k, v in dict1.items():
    # if the key of dict1 exists also in dict2
    if k in dict2.keys():
        # get its value (the keys-to-be for the new dict3)
        new_key = dict2[k]
        # if the new key is already in the new dict
        if new_key in dict3.keys():
            # appends new dict entry to dict3
            dict3[new_key].update({k: v})
        # otherwise create a new entry
        else:
            dict3[new_key] = {k: v}
    # if there is no corresponding mapping present
    else:
        # treat the original key as the new key and add to dict3
        no_map = k
        dict3[no_map] = {k: v}