How to merge two dictionaries in Python?
Python makes merging two dictionaries easy. Below you can find an example created directly in the Python interpreter. It defines two dictionaries, a
and b
, and then it creates a new dictionary c
by merging two previously created dictionaries.
$ python3
Python 3.8.3 (default, May 29 2020, 00:00:00)
[GCC 10.1.1 20200507 (Red Hat 10.1.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {'name': 'John', 'isAdmin': False}
>>> b = {'isAdmin': True, 'age': 42}
>>> c = {**a,**b}
>>> a
{'name': 'John', 'isAdmin': False}
>>> b
{'isAdmin': True, 'age': 42}
>>> c
{'name': 'John', 'isAdmin': True, 'age': 42}
This approach has one limitation. It does not merge nested dictionaries. If both a
and b
contain nested dictionary, the nested one from the b
would override the one from a
without merging its values.
$ python3
Python 3.8.3 (default, May 29 2020, 00:00:00)
[GCC 10.1.1 20200507 (Red Hat 10.1.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {'name': 'John', 'isAdmin': False, 'data': {'foo': 'bar'}}
>>> b = {'isAdmin': True, 'age': 42, 'data': {'key': 'value'}}
>>> c = {**a,**b}
>>> a
{'name': 'John', 'isAdmin': False, 'data': {'foo': 'bar'}}
>>> b
{'isAdmin': True, 'age': 42, 'data': {'key': 'value'}}
>>> c
{'name': 'John', 'isAdmin': True, 'data': {'key': 'value'}, 'age': 42}