EN
Python - copy dictionary
0 points
In this article, we would like to show you how to copy dictionary in Python.
Quick solution:
xxxxxxxxxx
1
dict2 = dict1.copy()
In this example, we use copy()
method to create a copy of my_dict
dictionary.
xxxxxxxxxx
1
my_dict = {
2
"id": 1,
3
"name": "Tom",
4
"age": 25
5
}
6
7
dict_copy = my_dict.copy()
8
9
print(dict_copy.items()) # [('id', 1), ('name', 'Tom'), ('age', 25)]
Output:
xxxxxxxxxx
1
dict_items([('id', 1), ('name', 'Tom'), ('age', 25)])
Note:
You can't simply use
dict2 = dict1
, becausedict2
will only be a reference todict1
. Any change indict1
will automatically cause the change indict2
.