In this paper, we describe the method of implementing two dictionaries (dict) merging in Python, and share them for your reference. Here's how:
The existing two dictionaries are dict as follows:
DICT1={1:[1,11,111],2:[2,22,222]}DICT2={3:[3,33,333],4:[4,44,444]}
Merge two dictionaries to get a similar:
{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) ' 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 (+)) ' 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 I N Range (+)) ' Dictmerged3=dict (Dict1) ' Dictmerged3.update (dict2) ' 100000 loops, Best of 3:7.09 usec per loop$ Pyth On-m timeit-s ' dict1=dict2=dict ((i,i) for I in range) ' Dictmerged4=dict1.copy () ' Dictmerged4.update (dict2) ' 100000 loops, Best of 3:6.73 usec per loop
Hopefully this article will help you with Python programming.