In looking at the methods for merging a dictionary in python, I have found two different methods that appear to have the same functionality.
{**dict1, **dict2}
and
dict1 | dict2
Aside from the latter only being available in 3.9 and above, it seems as though these two methods have the same functionality. That is, they both take in two dictionaries like the following:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
and return {'a': 1, 'b': 2, 'c': 3, 'd': 4}
My question is, is one of these methods dramatically (or even slightly) quicker than the other? Are there any other differences in these two methods?
EDIT Thanks for all the replies. In general, it seems as though the two methods listed above aren't significantly different in speed.
One note that was pointed out in the comments is that the ChainMap()
function in the collections
library does show some improvements when dealing with dictionaries of sufficient scale:
python3 -m timeit -n 1000 "x={'x_'+str(i):True for i in range(10000)};y={'y_'+str(i):True for i in range(10000)};x|y"
1000 loops, best of 5: 7.22 msec per loop
python3 -m timeit -n 1000 "from collections import ChainMap;x={'x_'+str(i):True for i in range(10000)};y={'y_'+str(i):True for i in range(10000)};ChainMap(x,y)"
1000 loops, best of 5: 4.16 msec per loop