Python Data Structures: Dictionaries and Sets 4 — Questions and Answers
Question 1: What does `{} == set()` evaluate to?
- True
- False (Correct answer)
- TypeError
- None
Correct answer: False
`{}` creates an empty dictionary, not an empty set; `set()` creates an empty set, so they are not equal.
Question 2: Given `d = {'x': 10, 'y': 20}`, what is `list(d)`?
- [10, 20]
- [('x', 10), ('y', 20)]
- ['x', 'y'] (Correct answer)
- [{'x': 10}, {'y': 20}]
Correct answer: ['x', 'y']
Iterating over a dictionary yields its keys, so `list(d)` produces a list of keys.
Question 3: What is the output of `s = {3, 1, 2}; print(min(s))`?
- 3
- 1 (Correct answer)
- TypeError
- Sets are unordered, so min() is undefined
Correct answer: 1
`min()` works on any iterable including sets and returns the smallest element, which is 1.
Question 4: What does `{1, 2, 3} - {2, 3, 4}` return?
- {1} (Correct answer)
- {4}
- {1, 4}
- {2, 3}
Correct answer: {1}
The `-` operator on sets returns the difference: elements in the left set that are not in the right set.
Question 5: Which approach creates a dictionary from two lists `keys` and `values`?
- dict(keys, values)
- {keys: values}
- dict(zip(keys, values)) (Correct answer)
- keys.merge(values)
Correct answer: dict(zip(keys, values))
`zip(keys, values)` pairs elements together and `dict()` converts those pairs into a dictionary.
Question 6: What does `collections.defaultdict(list)` do when you access a missing key?
- Raises KeyError
- Returns None
- Creates an empty list for that key (Correct answer)
- Returns an empty list without creating the key
Correct answer: Creates an empty list for that key
`defaultdict` automatically creates a default value (here an empty list) and stores it when a missing key is accessed.
Question 7: What is the output of `d = {'a': 1}; d.update({'a': 2, 'b': 3}); print(d)`?
- {'a': 1, 'b': 3}
- {'a': 2}
- {'a': 2, 'b': 3} (Correct answer)
- {'a': 1, 'a': 2, 'b': 3}
Correct answer: {'a': 2, 'b': 3}
`update()` merges the given dict into `d`, overwriting existing keys with new values and adding new keys.
What does `{} == set()` evaluate to?