You can not copy one dictionary to another dictionary variable by simply assigning it with an equal sign (dictionary_1 == dictionary_2
).
In this case, dictionary_2
is the only reference to dictionary_1
, and when you make changes to dictionary_1
, those changes automatically appear in dictionary_2
.
The copy()
function in Python allows you to copy a dictionary.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_dictionary_copy = company_dictionary.copy()
print(company_dictionary_copy)
{'name': 'Google', 'country': 'USA', 'start_year': 1995}
In the above example, we copy the company dictionary using the copy()
function. In the output, you can see that the new copy company dictionary (copy_company_dictionary
) matches the original company dictionary (company_dictionary
).
You can also copy the dictionary using Python built-in dict()
function.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_dictionary_copy = dict(company_dictionary)
print(company_dictionary_copy)
{'name': 'Google', 'country': 'USA', 'start_year': 1995}
In the above example, we copy the company dictionary using the dict()
function.