Python Data Structures: Dictionaries and Sets 3 — Questions and Answers
Question 1: What is the output of `d = {}; d[('a', 'b')] = 1; print(len(d))`?
- TypeError
- 2
- 1 (Correct answer)
- 0
Correct answer: 1
Tuples are hashable and can be used as dictionary keys; the dictionary has one key-value pair so its length is 1.
Question 2: Which expression produces a frozenset?
- frozenset([1, 2, 3]) (Correct answer)
- {1, 2, 3}.freeze()
- frozen({1, 2, 3})
- immutable({1, 2, 3})
Correct answer: frozenset([1, 2, 3])
`frozenset()` accepts an iterable and returns an immutable, hashable set.
Question 3: What does `{k: v for k, v in [('a', 1), ('b', 2)]}` produce?
- [('a', 1), ('b', 2)]
- {'a': 1, 'b': 2} (Correct answer)
- {('a', 1), ('b', 2)}
- TypeError
Correct answer: {'a': 1, 'b': 2}
This dict comprehension unpacks each two-element tuple into key-value pairs, building a dictionary.
Question 4: What is the result of `{1, 2} | {3, 4}`?
- {1, 2, 3, 4} (Correct answer)
- {}
- TypeError
- {1, 2}
Correct answer: {1, 2, 3, 4}
The `|` operator on sets returns the union — all elements from both sets with no duplicates.
Question 5: Which statement about Python dictionaries is TRUE as of Python 3.7+?
- Keys must be strings
- Dictionaries are unordered
- Insertion order is preserved (Correct answer)
- Keys can be lists
Correct answer: Insertion order is preserved
Since Python 3.7, dictionaries maintain insertion order as part of the language specification.
Question 6: What does `d.items()` return?
- A list of keys
- A list of values
- A view of (key, value) tuples (Correct answer)
- A copy of the dictionary
Correct answer: A view of (key, value) tuples
`dict.items()` returns a dynamic view object of (key, value) pairs that reflects changes to the dictionary.
Question 7: What happens when you try to add a list to a set: `s = {1, 2}; s.add([3, 4])`?
- The list is added as an element
- The list's items are added individually
- TypeError: unhashable type (Correct answer)
- ValueError
Correct answer: TypeError: unhashable type
Lists are mutable and unhashable, so they cannot be added to a set; Python raises TypeError.
What is the output of `d = {}; d[('a', 'b')] = 1; print(len(d))`?