0
0
Pythonprogramming~20 mins

Overwrite vs append behavior in Python - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Overwrite vs Append
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output when overwriting a dictionary key?

Consider the following Python code that assigns values to the same dictionary key multiple times. What will be the final content of the dictionary?

Python
d = {}
d['key'] = 1
d['key'] = 2
d['key'] = 3
print(d)
A{'key': 3}
B{'key': 1}
C{'key': [1, 2, 3]}
DKeyError
Attempts:
2 left
💡 Hint

Think about what happens when you assign a new value to an existing key in a dictionary.

Predict Output
intermediate
2:00remaining
What happens when appending to a list inside a dictionary?

Look at this code that appends values to a list stored in a dictionary. What is the output?

Python
d = {'numbers': []}
d['numbers'].append(1)
d['numbers'].append(2)
d['numbers'].append(3)
print(d)
ATypeError
B{'numbers': 3}
C{'numbers': []}
D{'numbers': [1, 2, 3]}
Attempts:
2 left
💡 Hint

Appending adds items to the existing list inside the dictionary.

Predict Output
advanced
2:00remaining
What is the output of this code mixing overwrite and append?

What will be printed by this code?

Python
d = {}
d['a'] = [1]
d['a'].append(2)
d['a'] = [3]
d['a'].append(4)
print(d)
A{'a': [3, 4]}
B{'a': [1, 2, 3, 4]}
C{'a': [1, 2]}
DAttributeError
Attempts:
2 left
💡 Hint

Notice when the list is overwritten and when append is called.

Predict Output
advanced
2:00remaining
What error occurs when appending to a non-list value?

What happens when you try to append to a dictionary value that is an integer?

Python
d = {'x': 10}
d['x'].append(5)
AKeyError
BTypeError
CAttributeError
DNo error, output: {'x': [10, 5]}
Attempts:
2 left
💡 Hint

Think about what types support the append method.

🧠 Conceptual
expert
2:00remaining
How many items are in the dictionary after this code runs?

Consider this code snippet. How many key-value pairs does the dictionary contain at the end?

Python
d = {}
for i in range(3):
    d['key'] = i
print(len(d))
A3
B1
C0
DKeyError
Attempts:
2 left
💡 Hint

Think about whether the key 'key' is added multiple times or overwritten.