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