合并多值词典

时间:2017-06-06 12:21:44

标签: python python-2.7 dictionary

假设我有两个字典,每个键有多个值:

Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}

我想将它们合并到一个字典中,如下所示:

mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }

3 个答案:

答案 0 :(得分:2)

循环键的并集,并使用dict.get和默认值[0, 0]

>>> dict1 = {'key1' : [1, 2]}
>>> dict2 = {'key1' : [3, 4], 'key2' : [5, 6]}
>>>
>>> {k:dict1.get(k, [0, 0]) + dict2.get(k, [0, 0]) for k in dict1.viewkeys() | dict2.viewkeys()}
{'key2': [0, 0, 5, 6], 'key1': [1, 2, 3, 4]}

答案 1 :(得分:1)

这应该这样做,并涵盖Dict1具有Dict2没有的密钥的可能性:

Dict1 = {'key1': ['value1', 'value2'], 'key3': ['value7', 'value8']}
Dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5', 'value6']}

mergedDict = {k: [0, 0] + v  if k not in Dict1 else Dict1[k] + v for k, v in Dict2.items()}
mergedDict.update({i: j + [0, 0] for i, j in Dict1.items() if i not in Dict2})
#{'key3': ['value7', 'value8', 0, 0], 'key2': [0, 0, 'value5', 'value6'], 'key1': ['value1', 'value2', 'value3', 'value4']}

答案 2 :(得分:0)

尝试defaultdict

from collections import defaultdict
dict1  = { 'key1' : ['value1','value2'] }
dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5','value6']}
dict3 = defaultdict(list)
for d1, d2 in dict1.items() + dict2.items():
    dict3[d1].extend(d2)
dict(dict3) #convert defaultdict to dict

输出:

{'key1': ['value1', 'value2', 'value3', 'value4'],
 'key2': ['value5', 'value6']}