0

Lets say I have two dictionaries with multiple values per key:

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

I want to merge them into one dictionary like this:

mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }
  • 1
    possible duplicate https://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression – user3764893 Jun 06 '17 at 12:23
  • did you try any code? – thavan Jun 06 '17 at 12:25
  • What about repeated values? If there is value1 for key1 in Dict1 and value1 for key1 in Dict2 should the restulting dictionary have two occurences of value1 for key1, or just one? – Błotosmętek Jun 06 '17 at 12:46
  • @thavan yes i did, using something like mergedDict[key].append(value) but it would just append them not index them like I want – Mohsin Khalid Jun 06 '17 at 19:15
  • @Błotosmętek yes the resulting dict should have two occurences of value1 something like key1 : [value1,value2,value1,value3] – Mohsin Khalid Jun 06 '17 at 19:17

3 Answers3

2

Loop over the union of the keys and use dict.get with the default value [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]}
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • thanks for the answer man, I'll accept it just have to test it. One more request can we do this for more than two dictionaries? like four? – Mohsin Khalid Jun 06 '17 at 19:31
  • works like a charm buddy, can we do it for more than two dictionaries? – Mohsin Khalid Jun 06 '17 at 19:39
  • @MohsinKhalid yes, but then we need a clearer rule how the padding should work. Always two zeros when a key is missing from one dictionary? – timgeb Jun 07 '17 at 08:13
1

This should do it, and covers possibity of Dict1 having keys that Dict2 doesn't:

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']}
zipa
  • 27,316
  • 6
  • 40
  • 58
0

Try with 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

Output:

{'key1': ['value1', 'value2', 'value3', 'value4'],
 'key2': ['value5', 'value6']}
Tiny.D
  • 6,466
  • 2
  • 15
  • 20