Python dictionary MCQ questions with answers
Keys, values and the methods that read and change them.
0 of 20 answered
Question 1 · Easy
What is the output of this code?
stock = {'apple': 5, 'banana': 0} print(stock.get('cherry', 10), stock.get('banana', 10))
Show the answer
Answer: A
Run this code in the editorget(key, default)returns the default only when the key is missing.'cherry'is missing, so it gives 10;'banana'exists, so its stored value 0 comes back even though 0 is falsy.Question 2 · Easy
What is the output of this code?
marks = {'Ravi': 70, 'Meena': 85} marks.update({'Ravi': 75, 'John': 60}) print(marks)
Show the answer
Answer: B
Run this code in the editorupdate()overwrites the value of a key that already exists and adds new keys at the end. An existing key keeps its original position, so'Ravi'stays first with the new value 75.Question 3 · Easy
What is the output of this code?
ages = {'Tom': 12, 'Ann': 15} for item in ages: print(item, end=' ')
Show the answer
Answer: C
Looping over a dictionary gives its keys, in insertion order. Use
Run this code in the editorages.values()for the values orages.items()for key-value pairs.Question 4 · Easy
What is the output of this code?
d = {'x': 1, 'y': 2, 'z': 3} value = d.pop('y') print(value, d)
Show the answer
Answer: D
Run this code in the editorpop(key)removes that key from the dictionary and returns its value, here 2. It ispopitem()that returns a key-value pair, and it always takes the last item.Question 5 · Easy
What is the output of this code?
squares = {n: n * n for n in range(1, 4)} print(squares)
Show the answer
Answer: B
Run this code in the editorrange(1, 4)gives 1, 2 and 3, stopping before 4. Each pass adds the keynwith the valuen * n, and curly braces withkey: valuemake a dictionary.Question 6 · Easy
Which error does this code raise?
capitals = {'India': 'New Delhi', 'Japan': 'Tokyo'} print(capitals['France'])
Show the answer
Answer: B, KeyError: 'France'
Square brackets with a missing key raise
Run this code in the editorKeyError. Usecapitals.get('France')to getNoneinstead, or check with'France' in capitalsfirst.Question 7 · Easy
In what order does a
forloop visit the keys of a dictionary in Python 3.13?Show the answer
Answer: A, The order in which the keys were inserted
Since Python 3.7, dictionaries keep insertion order as a language guarantee, so keys come back in the order they were added. Sets are different: their order is not defined.
Question 8 · Easy
Which expression builds
{'a': 1, 'b': 2}fromkeys = ['a', 'b']andvalues = [1, 2]?Show the answer
Answer: C
zip()pairs the items position by position, anddict()turns the pairs into keys and values.dict([keys, values])treats each list as one pair, giving{'a': 'b', 1: 2}; the other two raiseTypeError.Question 9 · Medium
What is the output of this code?
d = {'a': 1, 'b': 2, 'a': 3} print(d, len(d))
Show the answer
Answer: C
A key can appear only once. The later
Run this code in the editor'a': 3overwrites the value, but the key keeps the position where it first appeared, so the dictionary is{'a': 3, 'b': 2}with two keys.Question 10 · Medium
What is the output of this code?
groups = {} groups.setdefault('a', []).append(1) groups.setdefault('a', []).append(2) print(groups)
Show the answer
Answer: D
Run this code in the editorsetdefault()inserts the default only when the key is missing, and either way returns the value stored under the key. The second call finds the existing list and returns it, so both appends go into the same list.Question 11 · Medium
What is the output of this code?
d = {1: 'one', 2: 'two'} print('one' in d, 2 in d, 'two' in d.values())
Show the answer
Answer: A
Run this code in the editorinon a dictionary checks the keys only, so'one' in dis False and2 in dis True. To search the values, test againstd.values().Question 12 · Medium
What is the output of this code?
word = 'banana' counts = {} for ch in word: counts[ch] = counts.get(ch, 0) + 1 print(counts)
Show the answer
Answer: B
Run this code in the editorcounts.get(ch, 0)returns 0 the first time a letter is seen, then its count so far, and 1 is added each time. Keys keep the order they were first inserted (b, a, n); they are not sorted.Question 13 · Medium
What is the output of this code?
d = {'a': 1} keys = d.keys() d['b'] = 2 print(list(keys))
Show the answer
Answer: C
Run this code in the editorkeys()returns a view, not a copy: it always reflects the current keys of the dictionary. The key added after the view was made shows up when the view is turned into a list.Question 14 · Medium
Which error does this code raise?
ages = {'Tom': 12, 'Ann': 15} for name, age in ages: print(name, age)
Show the answer
Answer: C, ValueError: too many values to unpack (expected 2)
Looping over a dictionary gives keys only. The first key is the string
Run this code in the editor'Tom', and unpacking its three characters into two names raisesValueError. Loop overages.items()to get key-value pairs.Question 15 · Medium
Which values can be used as dictionary keys?
Show the answer
Answer: D, Any hashable value, such as a number, a string or a tuple of hashable items
Keys must be hashable so the dictionary can find them by hash. Numbers, strings,
Noneand tuples of hashable items qualify; lists, sets and dictionaries are mutable and raiseTypeErroras keys. Values can be anything.Question 16 · Medium
Which line removes the key
'temp'fromdand raises no error when the key is missing?Show the answer
Answer: D
With a second argument,
pop()returns that default instead of raising when the key is absent.delandpop()without a default raiseKeyError, and dictionaries have noremove()method.Question 17 · Hard
What is the output of this code?
original = {'name': 'Ana', 'scores': [80, 90]} clone = original.copy() clone['name'] = 'Bo' clone['scores'].append(70) print(original)
Show the answer
Answer: D
Run this code in the editorcopy()is shallow: the new dictionary has its own keys but shares the same value objects. Rebindingclone['name']affects only the copy, while appending to the shared list changes it for both.copy.deepcopy()copies nested values too.Question 18 · Hard
What is the output of this code?
d = {1: 'int', 1.0: 'float', True: 'bool'} print(d)
Show the answer
Answer: A
Run this code in the editor1,1.0andTrueare equal and have the same hash, so they are one and the same key. The key keeps its first spelling,1, and each later entry overwrites the value, leaving{1: 'bool'}.Question 19 · Hard
Which error does this code raise?
stock = {'pen': 0, 'ink': 4, 'pad': 0} for item in stock: if stock[item] == 0: del stock[item]
Show the answer
Answer: A, RuntimeError: dictionary changed size during iteration
A dictionary must not change size while a loop is iterating over it, so deleting
Run this code in the editor'pen'inside the loop raisesRuntimeErroron the next step. Loop over a copy of the keys,list(stock), or build a new dictionary with a comprehension.Question 20 · Hard
After
d = dict.fromkeys(['a', 'b'], []), what doesd['a'].append(1)do?Show the answer
Answer: B, Adds 1 to one list that both keys share, so
d['b']is[1]toofromkeys()stores the same default object under every key; it does not copy it. With a mutable default such as a list, a change made through one key shows under all of them.{k: [] for k in keys}makes a new list per key.
Keep going
- Read the lesson behind these questions: Dictionaries in the PythonBook
- Next topic: Python set MCQ questions with answers
- Before this: Python tuple MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.