Python 3.6 merge dictionaries
In this post:
- Python 3.6 how to merge several dictionaries
- Python merge dictionaries (before 3.5)
- Python 2 merge dictionaries
- Python 2 merge dictionaries with itertools
- Merge of dictionaries with repetition of keys
You can check also : Python loop dictionary keys and values
Python 3.6 how to merge several dictionaries
Since python 3.5 you can use this syntax to merge two or more dictionaries(it's the fastest one):
merge = {**one, **two, **three}
Example of merging 3 dictionaries:
dictOne = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
dictTwo = {4: 'C#', 5: 'C++', 6: 'Cobol', 7:'Ruby'}
dictThree = {8: 'HTML', 9: 'CSS'}
dictMerge = {**dictOne, **dictTwo, **dictThree}
for k, v in dictMerge.items():
print(k, v)
result:
0 None
1 Python
2 Java
3 Javascript
4 C#
5 C++
6 Cobol
7 Ruby
8 HTML
9 CSS
Python merge dictionaries (before 3.5)
For older version this code can simulate merging of dictionaries:
dictMerge = dictOne.copy()
dictMerge.update(dictTwo)
dictMerge.update(dictThree)
Example of merging 3 dictionaries:
dictOne = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
dictTwo = {4: 'C#', 5: 'C++', 6: 'Cobol', 7:'Ruby'}
dictThree = {8: 'HTML', 9: 'CSS'}
dictMerge = dictOne.copy()
dictMerge.update(dictTwo)
dictMerge.update(dictThree)
for k, v in dictMerge.items():
print(k, v)
result:
0 None
1 Python
2 Java
3 Javascript
4 C#
5 C++
6 Cobol
7 Ruby
8 HTML
9 CSS
Python 2 merge dictionaries
For Python 2 merging is done by:
dictMerge = dict(dictOne.items() + dictTwo.items() + dictThree.items())
Example of merging 3 dictionaries:
dictOne = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
dictTwo = {4: 'C#', 5: 'C++', 6: 'Cobol', 7:'Ruby'}
dictThree = {8: 'HTML', 9: 'CSS'}
dictMerge = dict(dictOne.items() + dictTwo.items() + dictThree.items())
for k, v in dictMerge.items():
print(k, v)
result:
0 None
1 Python
2 Java
3 Javascript
4 C#
5 C++
6 Cobol
7 Ruby
8 HTML
9 CSS
Python 2 merge dictionaries with itertools
Another way to merge dictionaries in python 2 is with itertools(it's faster than previous one):
dictMerge = dict(itertools.chain(dictOne.iteritems(), dictTwo.iteritems(), dictThree.iteritems()))
Example of merging 3 dictionaries:
import itertools
dictOne = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
dictTwo = {4: 'C#', 5: 'C++', 6: 'Cobol', 7:'Ruby'}
dictThree = {8: 'HTML', 9: 'CSS'}
dictMerge = dict(itertools.chain(dictOne.iteritems(), dictTwo.iteritems(), dictThree.iteritems()))
for k, v in dictMerge.items():
print(k, v)
result:
0 None
1 Python
2 Java
3 Javascript
4 C#
5 C++
6 Cobol
7 Ruby
8 HTML
9 CSS
Merge of dictionaries with repetition of keys
note that in case of repetition of keys only one will be present in the merge:
dictOne = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
dictTwo = {1: 'C#', 2: 'C++', 4: 'Cobol', 0:'Ruby'}
dictMerge = {**dictOne, **dictTwo}
result:
0 Ruby
1 C#
2 C++
3 Javascript