0
0
Pythonprogramming~20 mins

Dictionary keys, values, and items in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Dictionary Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of dictionary keys() method
What is the output of this code snippet?
Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(list(my_dict.keys()))
A['a', 'b', 'c']
B['1', '2', '3']
C['a', 'b', 'c', 'd']
Ddict_keys(['a', 'b', 'c'])
Attempts:
2 left
๐Ÿ’ก Hint
The keys() method returns a view of the dictionary's keys. Converting it to a list shows the keys as a list.
โ“ Predict Output
intermediate
2:00remaining
Output of dictionary values() method
What will this code print?
Python
data = {'x': 10, 'y': 20}
vals = data.values()
print(sum(vals))
A30
B['10', '20']
CTypeError
Ddict_values([10, 20])
Attempts:
2 left
๐Ÿ’ก Hint
The values() method returns a view of values which can be summed directly.
โ“ Predict Output
advanced
2:00remaining
Output of iterating dictionary items
What is the output of this code?
Python
d = {'one': 1, 'two': 2}
for k, v in d.items():
    print(f"{k}:{v}")
A1\n2
B('one', 1)\n('two', 2)
Cone\ntwo
Done:1\ntwo:2
Attempts:
2 left
๐Ÿ’ก Hint
items() returns key-value pairs which are unpacked in the loop.
โ“ Predict Output
advanced
2:00remaining
Length of dictionary keys view
What does this code print?
Python
my_dict = {1: 'a', 2: 'b', 3: 'c'}
keys_view = my_dict.keys()
print(len(keys_view))
ATypeError
B3
Cdict_keys([1, 2, 3])
D0
Attempts:
2 left
๐Ÿ’ก Hint
The keys view supports len() to get the number of keys.
โ“ Predict Output
expert
2:00remaining
Output of modifying dictionary during iteration
What happens when this code runs?
Python
d = {'a': 1, 'b': 2, 'c': 3}
for k in d.keys():
    if k == 'b':
        d.pop(k)
print(d)
A{'a': 1, 'c': 3}
B{'a': 1, 'b': 2, 'c': 3}
CRuntimeError: dictionary changed size during iteration
D{'a': 1, 'b': 2}
Attempts:
2 left
๐Ÿ’ก Hint
Modifying a dictionary while iterating over its keys causes an error.