0
0
Pythonprogramming~20 mins

Adding and updating key-value pairs in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Dictionary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this dictionary update?
Consider the following Python code that updates a dictionary. What will be printed?
Python
data = {'a': 1, 'b': 2}
data['c'] = 3
data['a'] = 4
print(data)
A{'a': 1, 'b': 2}
B{'a': 1, 'b': 2, 'c': 3}
C{'a': 4, 'b': 2}
D{'a': 4, 'b': 2, 'c': 3}
Attempts:
2 left
๐Ÿ’ก Hint
Remember that assigning a value to an existing key updates it.
โ“ Predict Output
intermediate
2:00remaining
What does this code print after using update()?
Look at this code snippet. What will be the output after the update method?
Python
info = {'name': 'Alice', 'age': 25}
info.update({'age': 30, 'city': 'NY'})
print(info)
A{'name': 'Alice', 'age': 30, 'city': 'NY'}
B{'name': 'Alice', 'age': 25, 'city': 'NY'}
C{'name': 'Alice', 'city': 'NY'}
D{'age': 30, 'city': 'NY'}
Attempts:
2 left
๐Ÿ’ก Hint
The update method changes existing keys and adds new ones.
โ“ Predict Output
advanced
2:30remaining
What is the output when updating nested dictionaries?
What will this code print?
Python
settings = {'display': {'brightness': 70, 'contrast': 50}}
settings['display']['brightness'] = 80
settings['sound'] = {'volume': 40}
print(settings)
A{'display': {'brightness': 70, 'contrast': 50}, 'sound': {'volume': 40}}
B{'display': {'brightness': 80, 'contrast': 50}}
C{'display': {'brightness': 80, 'contrast': 50}, 'sound': {'volume': 40}}
D{'display': {'brightness': 70, 'contrast': 50}, 'sound': 40}
Attempts:
2 left
๐Ÿ’ก Hint
Updating nested dictionary keys changes the inner dictionary values.
โ“ Predict Output
advanced
2:00remaining
What error does this code raise?
What error will this code produce?
Python
d = {'x': 1}
d[2,3] = 5
print(d)
A{'x': 1, (2, 3): 5}
BTypeError
CSyntaxError
DKeyError
Attempts:
2 left
๐Ÿ’ก Hint
Can tuples be used as dictionary keys?
โ“ Predict Output
expert
3:00remaining
What is the final dictionary after these updates?
What will be printed after running this code?
Python
d = {'a': 1, 'b': 2}
updates = [('a', 3), ('c', 4), ('b', 5)]
for k, v in updates:
    d[k] = v
print(d)
A{'a': 1, 'b': 2, 'c': 4}
B{'a': 3, 'b': 5, 'c': 4}
C{'a': 3, 'b': 2, 'c': 4}
D{'a': 1, 'b': 5, 'c': 4}
Attempts:
2 left
๐Ÿ’ก Hint
Each tuple updates or adds a key-value pair in the dictionary.