4. Aliasing and Copying¶
Because dictionaries are mutable, like lists, you need to be aware that aliasing can also occur with dictionaries. Whenever two variables refer to the same dictionary object, changes to one affect the other. For example, opposites
is a dictionary that contains pairs of opposites.
As you can see from the is
operator, alias
and opposites
refer to the same object.
If you want to modify a dictionary and keep a copy of the original, use the dictionary copy
method. Since acopy is a copy of the dictionary, changes to it will not effect the original. This is the dictionary equivalent to list cloning.
acopy = opposites.copy()
acopy['right'] = 'left' # does not change opposites
Check your understanding
- 23
- my_dict and your_dict are both names for the same dictionary.
- None
- The dictionary is mutable so changes can be made to the keys and values.
- 999
- Yes, since your_dict is an alias for my_dict, the value for the key elephant has been changed.
- Error, there are two different keys named elephant.
- There is only one dictionary with only one key named elephant. The dictionary has two different names, my_dict and your_dict.
What is printed by the following statements?
my_dict = {"cat":12, "dog":6, "elephant":23, "bear":20}
your_dict = my_dict
your_dict["elephant"] = 999
print(my_dict["elephant"])