Python DICTionary HowTo (Page: 2)
How to copy two dictionaries
It is possible to create new dictionary identical to already existing by copying. First of all, it is important to know, that if you just use operation = you will copy the reference to the dictionary and then two variables will point to the same dictionary!
How to copy reference to dictionary
By simple copying = you will create the reference to the same objsut, which is not what you usually intend to do
Example of potentially WRONG dictionary copy code:
d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d2 = d1
d2['e'] = 5
print(d1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
It is possible to see, that by modification of d2 we also modify d1.
How to make shallow copy of dictionary
If the dictionary simple, with one layer of data, then shallow copy will work perfect. It is possible to make shallow copy with dict() and .copy() functions, which are in fact equivalent. If the dictionary have few layers of deepness, then it will produce an error, because shallow copy copies only references from inside the dictionary
d1 = {'a': 1, 'b': 2, 'list':[1,2,3]}
d2 = dict(d1)
d3 = d1.copy()
d1['C'] = -3
d2['c'] = 3
print(d1) # {'a': 1, 'b': 2, 'list': [1, 2, 3], 'C': -3}
print(d2) # {'a': 1, 'b': 2, 'list': [1, 2, 3], 'c': 3}
print(d3) # {'a': 1, 'b': 2, 'list': [1, 2, 3]}
# BUT!!!!
d1['list'].append(4)
print(d1) # {'a': 1, 'b': 2, 'list': [1, 2, 3, 4]}
print(d2) # {'a': 1, 'b': 2, 'list': [1, 2, 3, 4]}
print(d3) # {'a': 1, 'b': 2, 'list': [1, 2, 3, 4]}
How to make deep copy of dictionary
Proper full copy of dictionary can be made by copy / deepcopy of the copy module.
import copy
d1 = {'a': 1, 'b': 2, 'list':[1,2,3]}
d2 = copy.deepcopy(d1)
d1['list'].append(4)
print(d1) # {'a': 1, 'b': 2, 'list': [1, 2, 3, 4]}
print(d2) # {'a': 1, 'b': 2, 'list': [1, 2, 3]}
For safety it is better to always use deep copy of dictionaries
How to merge two dictionaries in Python
The preferred way of merging to dictionaries is to merge ** of dictionaries. If the keys are overlapped in two dictionaries, then the last value will be used
d1 = {'a':0, 'b':1, 'c':2}
d2 = {'c':3, 'd':4, 'e':5}
merge = {**d1, **d2}
print(merge) # {'a': 0, 'b': 1, 'c': 3, 'd': 4, 'e': 5}
This techniques can be used for merging of unlimited number of dictionaries
Published: 2021-10-13 14:31:51
Updated: 2021-10-20 14:27:27