Python DICTionary HowTo »

My Coding > Programming language > Python > Python DICTionary HowTo

Python DICTionary HowTo (Page: 2)

Go to Page:

  1. Python dictionary - basics;
  2. Copying/Merging two dictionaries;
  3. Dictionary sorting;

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

Go to Page: 1; 2; 3;


Published: 2021-10-13 14:31:51
Updated: 2021-10-20 14:27:27

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.