7 Different Ways to Merge Dictionaries in Python

Different ways of merging dictionaries in Python

Photo by bongkarn thanyakij from Pexels

Merging Python dictionaries

In python, we can merge two dictionaries using different methods. Let’s learn about this in this article.

Refer to my article for Python dictionaries.

Different ways of merging two dictionaries

Image Source: Author

1. dict.update()

update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

Example 1:Merging two dictionaries d1,d2 having unique keys using the update() method.

d1.update(d2)

Update d1- dictionary with key-value pairs from d1 and d2.

The return type is None. It will update the original dictionary d1.

d1={'a':1,'b':2}
d2={'c':3,'d':4}
d1.update(d2)
print (d1)
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Example 2: Merging two dictionaries having the common keys with different values using an update() method.

d1.update(d2)
Update d1- dictionary with key-value pairs from d1 and d2.Keys that are common in both d1 and d2 will contain values from d2.

Image Source: Author
d1={'a':1,'b':2}
d2={'a':99,'c':3,'d':4}
d1.update(d2)
print (d1)
#Output:{'a': 99, 'b': 2, 'c': 3, 'd': 4}

d2.update(d1)

Update d2- dictionary with key-value pairs from d1 and d2. Keys that are common in both d1 and d2 will contain values from d1.

Image Source: Author
d1={'a':1,'b':2}
d2={'a':99,'c':3,'d':4}
d2.update(d1)
print (d2)
#Output:{'a': 1, 'c': 3, 'd': 4, 'b': 2}

The return type is None. It only updates the original dictionary (d2).

d1={'a':1,'b':2}
d2={'a':99,'c':3,'d':4}
print (d2.update(d1))
#Output:None

2. Using deepcopy() and dict.update()

If we don’t want to update the original dictionary means, we can create a copy of the dictionary and update it.

To merge two dictionaries d1 and d2, create deepcopy(d1) as d and then do the update method. In this way, the original dictionary will not be modified.

d=deepcopy(d1)
d.update(d2)

Refer to my story for deepcopy.

from copy import deepcopy
d1={'a':1,'b':2,'c':3}
d2={'a':99,'d':4}
d=deepcopy(d1)
d.update(d2)
print (d)
#Output:{'a': 99, 'b': 2, 'c': 3, 'd': 4}

3. {**d1,**d2}

d3={**d1,**d2}

A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key- pairs and earlier dictionary unpackings.

Image Source: Author

Merging two dictionaries having unique keys using **kwargs

d3={**d1,**d2}

It will expand the contents of dictionary d1 and d2 as a collection of key-value pairs and update the dictionary d3.

d1={'a':1,'b':2}
d2={'c':3,'d':4}
d3={**d1,**d2}
print (d3)
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Merging two dictionaries having common keys using **kwargs

d3={**d1,**d2}

It will expand the contents of dictionary d1 and d2 as a collection of key-value pairs and update the dictionary d3. 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.

Image Source: Author
d1={'a':1,'b':2}
d2={'a':99,'c':3,'d':4}
d3={**d1,**d2}
print (d3)
#Output:{'a': 99, 'b': 2, 'c': 3, 'd': 4}

Merging more than two dictionaries using **kwargs

d4={**d1,**d2,**d3}

It will expand the contents of dictionary d1,d2,d3 as a collection of key-value pairs, and update the dictionary d4.

Keys that are common in d1 and d2 will contain values from d2.
Keys that are common in d1 and d3 will contain values from d3.
Keys that are common in d1,d2, and d3 will contain values from d3.

Image Source: Author
d1={'a':1,'b':2}
d2={'a':99,'d':4}
d3={'c':3,'b':77}
d4={**d1,**d2,**d3}
print (d4)
#Output:{'a': 99, 'b': 77, 'd': 4, 'c': 3}

4. dict(d1,**d2)

d3=dict(d1,**d2)

d3 will contain key-value pair from d1 and d2.Keys that are common in d1 and d2 will contain values from d2.

Image Source: Author
d1={'a':1,'b':2}
d2={'a':99,'c':3}
d3=dict(d1,**d2)
print (d3)
#Output:{'a': 99, 'b': 2, 'c': 3}

d3=dict(d1,**d2)-This will work only when d2 is entirely string-keyed.

If int is given as a key in d2, it will raise TypeError.

d1={'a':1,'b':2}
d2={'a':99,1:3}
d3=dict(d1,**d2)
print (d3)
#Output:TypeError: keywords must be strings

d1 need not be string-keyed. Given int as a key for d1.

d1={'a':1,1:2}
d2={'a':99,'c':3}
d3=dict(d1,**d2)
print (d3)
#Output:{'a': 99, 1: 2, 'c': 3}

5. collections.ChainMap

ChainMap:
A ChainMap group’s multiple dictionary or other mappings together to create a single, updateable view.

collections.ChainMap(*maps)

Return Type is collections.ChainMap.
We can convert to dict using the dict() constructor.

Image Source: Author
d3=ChainMap(d1,d2)

keys which are common in d1 and d2 will have values from d1(first seen values)

Merging two dictionaries having unique keys using collections.ChainMap.

from collections import ChainMap
d1={'a':1,'b':2}
d2={'c':3,'d':4}
d3=ChainMap(d1,d2)
print (d3)
#Output:ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
print (dict(d3))
#Output:{'c': 3, 'd': 4, 'a': 1, 'b': 2}

Merging two dictionaries having the same keys. The keys which are common in d1 and d2 will contain values from d1 only(first seen value)

from collections import ChainMap
d1={'a':1,'b':2}
d2={'c':3,'d':4,'a':99}
d3=ChainMap(d1,d2)
print (d3)
#Output:ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'a': 99})
print (dict(d3))
#Output:{'c': 3, 'd': 4, 'a': 1, 'b': 2}

6.itertools.chain():

Makes an iterator that returns an element from the first iterable until its exhausted, then proceeds to the next iterable. It will treat consecutive sequences as a single sequence.
itertools.chain(*iterables)

Dictionary is also iterable, so we can use itertools.chain() to merge two dictionaries. The return type will be itertools.chain object. We can convert to dict using the dict() constructor.

Merging two dictionaries having unique keys using itertools.chain()

import itertools
d1={'a':1,'b':2}
d2={'c':3,'d':4}
num1=itertools.chain(d1.items(),d2.items())
#Returns an iterator object
print (num1)
#Output:<itertools.chain object at 0x029FE4D8>
#converting iterator object to dict object
print(dict(num1))
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Merging two dictionaries having common keys using itertools.chain()

Image Source: Author
import itertools
d1={'a':1,'b':2}
d2={'a':99,'d':4}
num1=itertools.chain(d1.items(),d2.items())
#Returns an iterator object
print (num1)
#Output:<itertools.chain object at 0x029FE4D8>
#converting iterator object to dict object
print(dict(num1))
#Output:{'a': 99, 'b': 2, 'd': 4}

7. Dictionary Comprehension

We can merge two dictionaries using dictionary comprehension.

Refer to my story of dictionary comprehension.

Merging two dictionaries having common keys using dictionary comprehension

Image Source: Author
d1={'a':1,'b':2}
d2={'c':3,'d':4,'a':99}
d3={k:v for d in (d1,d2) for k,v in d.items()}
print (d3)
#Output:{'a': 99, 'b': 2, 'c': 3, 'd': 4}

Merging two dictionaries having unique keys using dictionary comprehension

d1={'a':1,'b':2}
d2={'c':3,'d':4}
d3={k:v for d in (d1,d2) for k,v in d.items()}
print (d3)
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Conclusion

  • Python version used in all examples: Python 3.8.1
  • d1.update(d2) -Return type is None.It will update the original dictionary itself(d1).
  • {**d1,**d2} — Return type is dictionary.
  • collections.ChainMap– Return type is collections.ChainMap.
  • itertools.chain() -The return type is itertools.chain object
  • dict(d1,**d2)-This will work only when d2 is entirely string-keyed.
  • “last seen wins” — last seen values will overwrite the existing keys.
1. d1.update(d2)
2. {**d1,**d2} 
3. dict(d1,**d2)
4. itertool.chain()
5. dictionary comprehension.
  • “first seen wins” instead of “last seen wins”

1. collections.ChainMap


My other blog links

Merging Lists in Python

List, Set, Dictionary Comprehensions in Python


Resources

PEP-584

PEP-448

Dictionary displays

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s