nerdexam
Python_Institute

PCEP-30-02 · Question #49

What is the expected output of the following code? box = {} jars = {} crates = {} box['biscuit'] = 1 box['cake'] = 3 jars['jam'] = 4 crates['box'] = box crates['jars'] = jars print(len(crates[box]))

The correct answer is C. The code is erroneous. Option C is correct because the last line uses box (a dictionary object) as a key to look up a value in crates - but Python dictionaries are unhashable, meaning they cannot be used as dictionary keys, so this raises a TypeError: unhashable type: 'dict' at runtime. Option A (2)…

Question

What is the expected output of the following code? box = {} jars = {} crates = {} box['biscuit'] = 1 box['cake'] = 3 jars['jam'] = 4 crates['box'] = box crates['jars'] = jars print(len(crates[box]))

Options

  • A2
  • B1
  • CThe code is erroneous.
  • D4

How the community answered

(41 responses)
  • A
    17% (7)
  • B
    7% (3)
  • C
    73% (30)
  • D
    2% (1)

Explanation

Option C is correct because the last line uses box (a dictionary object) as a key to look up a value in crates - but Python dictionaries are unhashable, meaning they cannot be used as dictionary keys, so this raises a TypeError: unhashable type: 'dict' at runtime. Option A (2) is the tempting trap: if the code had used the string 'box' instead - crates['box'] - it would return the box dict with two keys ('biscuit' and 'cake'), giving len() of 2. Option B (1) has no logical basis in the code. Option D (4) is the value stored at jars['jam'], which is unrelated to what len(crates[...]) would return. Memory tip: Whenever you see a mutable object (dict, list) used as a dictionary key, flag it immediately - only immutable (hashable) types like strings, numbers, and tuples are valid keys in Python.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice