Python implements the method of merging two dictionaries (dict)
- 2020-04-02 14:07:57
- OfStack
This article provides an example of how two dictionaries (dict) can be merged in Python. Specific methods are as follows:
There are two dictionaries dict as follows:
dict1={1:[1,11,111],2:[2,22,222]}
dict2={3:[3,33,333],4:[4,44,444]}
Merging the two dictionaries results in something like:
{1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}
Method 1:
dictMerged1=dict(dict1.items()+dict2.items())
Method 2:
dictMerged2=dict(dict1, **dict2)
Method 2 is equivalent to:
dictMerged=dict1.copy()
dictMerged.update(dict2)
Or:
dictMerged=dict(dict1)
dictMerged.update(dict2)
Method 2 is much faster than method 1 and is tested with timeit as follows
$ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged1=dict(dict1.items()+dict2.items())'
10000 loops, best of 3: 20.7 usec per loop
$ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged2=dict(dict1,**dict2)'
100000 loops, best of 3: 6.94 usec per loop
$ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged3=dict(dict1)' 'dictMerged3.update(dict2)'
100000 loops, best of 3: 7.09 usec per loop
$ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged4=dict1.copy()' 'dictMerged4.update(dict2)'
100000 loops, best of 3: 6.73 usec per loop
I hope this article has helped you with your Python programming.