Consider the following Python code that assigns values to the same dictionary key multiple times. What will be the final content of the dictionary?
d = {}
d['key'] = 1
d['key'] = 2
d['key'] = 3
print(d)Think about what happens when you assign a new value to an existing key in a dictionary.
Assigning a value to an existing key in a dictionary overwrites the old value. So the final value for 'key' is 3.
Look at this code that appends values to a list stored in a dictionary. What is the output?
d = {'numbers': []}
d['numbers'].append(1)
d['numbers'].append(2)
d['numbers'].append(3)
print(d)Appending adds items to the existing list inside the dictionary.
The list under 'numbers' grows with each append call, so the final list is [1, 2, 3].
What will be printed by this code?
d = {}
d['a'] = [1]
d['a'].append(2)
d['a'] = [3]
d['a'].append(4)
print(d)Notice when the list is overwritten and when append is called.
After overwriting 'a' with [3], the previous list is lost. Then 4 is appended to the new list, so 'a' is [3, 4].
What happens when you try to append to a dictionary value that is an integer?
d = {'x': 10}
d['x'].append(5)Think about what types support the append method.
Integers do not have an append method, so calling append on d['x'] raises AttributeError.
Consider this code snippet. How many key-value pairs does the dictionary contain at the end?
d = {}
for i in range(3):
d['key'] = i
print(len(d))Think about whether the key 'key' is added multiple times or overwritten.
The key 'key' is overwritten in each loop iteration, so only one key remains in the dictionary.