Python Data Structures: Dictionaries and Sets 2 — Questions and Answers
Question 1: What is the output of `d = {'a': 1, 'b': 2}; print(d.get('c', 99))`?
- None
- KeyError
- 99 (Correct answer)
- 0
Correct answer: 99
`dict.get(key, default)` returns the default value when the key is not found, so 99 is returned.
Question 2: Which method removes a key from a dictionary and returns its value, raising KeyError if missing?
- .get()
- .pop() (Correct answer)
- .discard()
- .remove()
Correct answer: .pop()
`dict.pop(key)` removes the key and returns its value, raising KeyError if the key does not exist (unless a default is provided).
Question 3: What does `s = {1, 2, 3}; s.discard(5)` do?
- Raises KeyError
- Raises ValueError
- Does nothing silently (Correct answer)
- Adds 5 to the set
Correct answer: Does nothing silently
`set.discard()` removes the element if present but does nothing if the element is absent, unlike `set.remove()` which raises KeyError.
Question 4: What is the result of `{1, 2, 3} & {2, 3, 4}`?
- {1, 2, 3, 4}
- {2, 3} (Correct answer)
- {1, 4}
- {1, 2, 3, 2, 3, 4}
Correct answer: {2, 3}
The `&` operator computes set intersection, returning only elements common to both sets.
Question 5: Which of the following correctly merges dict `b` into dict `a`, overwriting duplicate keys with `b`'s values (Python 3.9+)?
- a.update(b)
- a | b (Correct answer)
- a.merge(b)
- a + b
Correct answer: a | b
In Python 3.9+, the `|` operator merges two dicts, with the right operand's values winning on duplicate keys.
Question 6: What is the time complexity of checking membership (`x in s`) in a Python set?
- O(n)
- O(log n)
- O(1) average (Correct answer)
- O(n²)
Correct answer: O(1) average
Set membership testing is O(1) average case because sets are implemented as hash tables.
Question 7: What does `dict.setdefault('key', [])` do when 'key' already exists in the dict?
- Overwrites the existing value with []
- Returns [] without changing the dict
- Returns the existing value without changing the dict (Correct answer)
- Raises KeyError
Correct answer: Returns the existing value without changing the dict
`setdefault` only sets the key to the default if the key is absent; if the key already exists it returns its current value unchanged.
What is the output of `d = {'a': 1, 'b': 2}; print(d.get('c', 99))`?