Editor

Python dictionary MCQ questions with answers

Keys, values and the methods that read and change them.

0 of 20 answered

  1. 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

    get(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.

    Run this code in the editor
  2. 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

    update() 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.

    Run this code in the editor
  3. 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 ages.values() for the values or ages.items() for key-value pairs.

    Run this code in the editor
  4. 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

    pop(key) removes that key from the dictionary and returns its value, here 2. It is popitem() that returns a key-value pair, and it always takes the last item.

    Run this code in the editor
  5. 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

    range(1, 4) gives 1, 2 and 3, stopping before 4. Each pass adds the key n with the value n * n, and curly braces with key: value make a dictionary.

    Run this code in the editor
  6. 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 KeyError. Use capitals.get('France') to get None instead, or check with 'France' in capitals first.

    Run this code in the editor
  7. Question 7 · Easy

    In what order does a for loop 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.

  8. Question 8 · Easy

    Which expression builds {'a': 1, 'b': 2} from keys = ['a', 'b'] and values = [1, 2]?

    Show the answer

    Answer: C

    zip() pairs the items position by position, and dict() turns the pairs into keys and values. dict([keys, values]) treats each list as one pair, giving {'a': 'b', 1: 2}; the other two raise TypeError.

  9. 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 'a': 3 overwrites the value, but the key keeps the position where it first appeared, so the dictionary is {'a': 3, 'b': 2} with two keys.

    Run this code in the editor
  10. 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

    setdefault() 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.

    Run this code in the editor
  11. 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

    in on a dictionary checks the keys only, so 'one' in d is False and 2 in d is True. To search the values, test against d.values().

    Run this code in the editor
  12. 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

    counts.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.

    Run this code in the editor
  13. 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

    keys() 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.

    Run this code in the editor
  14. 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 'Tom', and unpacking its three characters into two names raises ValueError. Loop over ages.items() to get key-value pairs.

    Run this code in the editor
  15. 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, None and tuples of hashable items qualify; lists, sets and dictionaries are mutable and raise TypeError as keys. Values can be anything.

  16. Question 16 · Medium

    Which line removes the key 'temp' from d and 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. del and pop() without a default raise KeyError, and dictionaries have no remove() method.

  17. 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

    copy() is shallow: the new dictionary has its own keys but shares the same value objects. Rebinding clone['name'] affects only the copy, while appending to the shared list changes it for both. copy.deepcopy() copies nested values too.

    Run this code in the editor
  18. 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

    1, 1.0 and True are 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'}.

    Run this code in the editor
  19. 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 'pen' inside the loop raises RuntimeError on the next step. Loop over a copy of the keys, list(stock), or build a new dictionary with a comprehension.

    Run this code in the editor
  20. Question 20 · Hard

    After d = dict.fromkeys(['a', 'b'], []), what does d['a'].append(1) do?

    Show the answer

    Answer: B, Adds 1 to one list that both keys share, so d['b'] is [1] too

    fromkeys() 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