4

I have 2 dictionaries

dict1 = {'color': {'attri': ['Black']}, 'diameter': {'attri': ['(300, 600)']}}

dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}}

I want to combine the 2 dictionaries such that

dict3 = {'color': {'op': 'in', 'attri': ['Black']}, 'diameter': {'op': 'range', 'attri': ['(300,600)']}}
Ma0
  • 15,057
  • 4
  • 35
  • 65
Aakash Patel
  • 274
  • 2
  • 17

4 Answers4

6

This method uses a defaultdict and is safe even if a key only appears in one of the dictionaries.

import itertools
import collections

dict3 = collections.defaultdict(dict)

for key, value in itertools.chain(dict1.items(), dict2.items()):
     dict3[key].update(value)

Proof -- applied to:

dict1 = {'color': {'attri':['Black']}, 'diameter': {'attri':['(300, 600)']}}
dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}}

the output of dict(dict3) is:

{'color': {'attri': ['Black'], 'op': 'in'},
'diameter': {'attri': ['(300, 600)'], 'op': 'range'},
'size': {'op': 'in'}}

Although looking at your expected output, you only want a result if the key appears in both dictionaries, in which case I'd do:

dict3 = {key: {**dict1[key], **dict2[key]} 
         for key in dict1.keys() & dict2.keys()}
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
5

Just use a mix of dict comprehensions and dict unpacking:

dict1 = {'color': {'attri':['Black']}, 'diameter': {'attri':['(300, 600)']}}
dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}}

dict3 = {n:{**dict1[n],**dict2[n]} for n in dict1}
MegaIng
  • 7,361
  • 1
  • 22
  • 35
  • Thanks This is working, How can I also do this if dict1 = {'color': ['Black'], 'diameter': ['(300, 600)']} – Aakash Patel Jun 06 '18 at 09:22
  • @AakashPatel What should happen then? – MegaIng Jun 06 '18 at 09:27
  • I am getting the following error :Traceback (most recent call last): File "C:/Users/AAKASH PATEL/Desktop/demo1.py", line 4, in dict3 = {n:{**dict1[n],**dict2[n]} for n in dict1} File "C:/Users/AAKASH PATEL/Desktop/demo1.py", line 4, in dict3 = {n:{**dict1[n],**dict2[n]} for n in dict1} TypeError: 'list' object is not a mapping – Aakash Patel Jun 06 '18 at 09:29
  • @AakashPatel Yes, because `list` can't be unpacked like that. It doesn't make sense to transform a `list` to a `dict`. What do you expect to happen? – MegaIng Jun 06 '18 at 12:10
3
res = {}
for item in dict1:
  res.setdefault(item, {})
  res[item].update(dict1[item])
  if item in dict2:
    res[item].update(dict2[item])
ravi
  • 10,994
  • 1
  • 18
  • 36
-1

For dictionaries x and y, z becomes a merged dictionary with values from y and from x.

In Python 3.5 or greater, :

z = {**x, **y}

In Python 2, (or 3.4 or lower) write a function:

def merge_two_dicts(x, y):
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z
and

z = merge_two_dicts(x, y)
Rubin bhandari
  • 1,873
  • 15
  • 20