Copy a Dictionary
Writing dict2 = dict1 does not give you a real copy of a dictionary. dict2 is then just a reference to dict1, so anything you change in dict1 automatically shows up in dict2 as well.
A real copy takes a different approach, and one good option is the built-in Dictionary method copy().
Example
Duplicate a dictionary by calling its copy() method:
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Make a copy of the dictionary using the copy() method and print the copy.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Using the dict() Function
A second way to get a copy is the built-in function dict().
Example
Duplicate a dictionary by calling dict():
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Make a copy of the dictionary using the built-in dict() function and print the copy.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)