Python merge dictionaries with common keys

I have two dictionaries and need to combine the values of similar keys in them. Here's an example:

dict1 = {'key1':[value11,value12,value13] , 'key2':[value21,value22,value23]}
dict2 = {'key1':[value14,value15] , 'key2':[value24,value25]}

I used :

dict3 = {}
for key in [dict1.viewkeys[] | dict2.keys[]]:
    if key in dict1: dict3.setdefault[key, []].append[dict1[key]]
    if key in dict2: dict3.setdefault[key, []].append[dict2[key]]

which gives me:

dict3 = {'key1':[[value11,value12,value13],[value14,value15]] , 'key2':[[value21,value22,value23],[value24,value25]]}

What I want is a simple one like:

Desired output :

 dict3 = {'key1':[value11,value12,value13,value14,value15] , 'key2':[value21,value22,value23,value24,value25]}

asked Aug 20, 2014 at 13:20

5

All you need to do is to modify append to extend which will then add the elements of the list rather than adding the list itself. See the list docs for more details on the difference between append and extend.

dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23']}
dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}

dict3 = {}
for key in set[].union[dict1, dict2]:
    if key in dict1: dict3.setdefault[key, []].extend[dict1[key]]
    if key in dict2: dict3.setdefault[key, []].extend[dict2[key]]

print[dict3]
# {'key2': ['value21', 'value22', 'value23', 'value24', 'value25'], 'key1': ['value11', 'value12', 'value13', 'value14', 'value15']}

Alternatively you could use a collections.defaultdict with the default set to list as shown below.

from collections import defaultdict
dict3 = defaultdict[list]

for key in set[].union[dict1, dict2]:
  for dic in [dict1, dict2]:
    if key in dic:
      dict3[key] += dic[key]

answered Aug 20, 2014 at 13:28

FfisegyddFfisegydd

48.9k14 gold badges139 silver badges118 bronze badges

6

You can do it much simpler but if you want to use your code just change append to extend

dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23']}
dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}

dict3 = {}
for key in [dict1.viewkeys[] | dict2.keys[]]:
    if key in dict1: dict3.setdefault[key, []].extend[dict1[key]]
    if key in dict2: dict3.setdefault[key, []].extend[dict2[key]]

print dict3

output:

{'key2': ['value21', 'value22', 'value23', 'value24', 'value25'], 'key1': ['value11', 'value12', 'value13', 'value14', 'value15']}

You can read this post about the difference ov append to extend

answered Aug 20, 2014 at 13:27

Kobi KKobi K

7,4676 gold badges39 silver badges83 bronze badges

Here is a generic method on which you can pass as many dict as you want as parameter.

>>> def mix_dict[*args]:
       res = {}
       for d in args:
           if not isinstance[d, dict]:
               continue
           for k, v in d.iteritems[]:
               res.setdefault[k, []]
               if isinstance[v, list]:
                   res[k].extend[v]
               else:
                   res[k].append[v]
       return res
>>> dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23']}
>>> dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}
>>> dict3 = mix_dict[dict1, dict2]
>>> print dict3
... {'key1': ['value11', 'value12', 'value13', 'value14', 'value15'],
     'key2': ['value21', 'value22', 'value23', 'value24', 'value25']}

answered Aug 20, 2014 at 13:35

Here is another way to do this.

You can support merging N dicts of lists into a single dict of lists with this function:

def mergeDoLs[*dicts]:
    def flatten[LoL]:
        return [e for l in LoL for e in l]

    rtr={k:[] for k in set[flatten[d.keys[] for d in dicts]]}
    for k, v in flatten[d.items[] for d in dicts]:
        rtr[k].extend[v]
    return rtr

To use:

>>> dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23'], 'key3':[1]}
>>> dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}
>>> dict3 = {'key3':[2]}
>>> mergeDoLs[dict1, dict2, dict3] 
{'key3': [1, 2], 'key2': ['value21', 'value22', 'value23', 'value24', 'value25'], 'key1': ['value11', 'value12', 'value13', 'value14', 'value15']}

answered Aug 20, 2014 at 13:40

dawgdawg

93.1k23 gold badges122 silver badges200 bronze badges

Use dict.update[] to merge two dictionaries keys: dict1['key1'].update[dict2['key1']]

answered Dec 28, 2019 at 18:09

BSalitaBSalita

7,9158 gold badges50 silver badges63 bronze badges

How do I merge dictionaries with common keys?

Merging two dictionaries having common keys using **kwargs Keys that are common in both d1 and d2 will contain values from d2. If d3={**d2,**d1} -Keys that are common in both d1 and d2 will contain values from d1.

How do you combine two dictionary values for common keys in Python?

Below are the eight standard methods by which you can merge two dictionaries in python..
1] Using update[] method..
2] Using merge[|] operator..
3] Using ** operator..
4] Unpacking the second dictionary..
5] Using collection.ChainMap[] method..
6] Using itertools. ... .
7] Using dictionary comprehension..
8] Add values of common keys..

How do I merge two dictionaries in Python?

Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id. # based on some value. Method #2: Using extend[] only.

Can you concatenate dictionary in Python?

Python concatenate dictionaries with same keys The counter holds the data in an unordered collection just like a hashable object. To concatenate the dictionary, I have used dictionary = dictionary1 + dictionary2. To get the output, I have used print[“dictionary”, str[dictionary]].

Chủ Đề