Data Structures: Dictionaries and Sets Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Data Structures: Dictionaries and Sets flashcards as text
What is the output of `d = {'a': 1, 'b': 2}; print(d.get('c', 99))`?
Answer: 99
`dict.get(key, default)` returns the default value when the key is not found, so 99 is returned.
Which method removes a key from a dictionary and returns its value, raising KeyError if missing?
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).
What does `s = {1, 2, 3}; s.discard(5)` do?
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.
What is the result of `{1, 2, 3} & {2, 3, 4}`?
Answer: {2, 3}
The `&` operator computes set intersection, returning only elements common to both sets.
Which of the following correctly merges dict `b` into dict `a`, overwriting duplicate keys with `b`'s values (Python 3.9+)?
Answer: a | b
In Python 3.9+, the `|` operator merges two dicts, with the right operand's values winning on duplicate keys.
What is the time complexity of checking membership (`x in s`) in a Python set?
Answer: O(1) average
Set membership testing is O(1) average case because sets are implemented as hash tables.
What does `dict.setdefault('key', [])` do when 'key' already exists in the dict?
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.