Dicts and Sets
Dicts — fast key-value lookup
Section titled “Dicts — fast key-value lookup”A dict maps hashable keys to arbitrary values. Since Python 3.7 the insertion order of keys is guaranteed and preserved.
scores = {'alice': 95, 'bob': 87}scores['carol'] = 92 # add a new keyprint(scores['alice']) # 95del scores['bob'] # remove a keyprint(scores) # {'alice': 95, 'carol': 92}Safe access: get and setdefault
Section titled “Safe access: get and setdefault”Accessing a missing key with [] raises KeyError.
Use .get() for a safe read with an optional default, or .setdefault() to insert a default value when the key is absent.
scores = {'alice': 95, 'bob': 87}unknown = scores.get('dave', 0) # returns 0 — no KeyErrorscores.setdefault('eve', 88) # inserts eve=88 only if absentprint(scores)# {'alice': 95, 'bob': 87, 'eve': 88}Iterating with .items()
Section titled “Iterating with .items()”.items() yields (key, value) pairs, which you can unpack directly in a for loop.
for name, score in scores.items(): print(f'{name}: {score}')You can also iterate over .keys() (default) or .values() independently.
Dict comprehensions
Section titled “Dict comprehensions”Like list comprehensions, dict comprehensions build a new dict in one expression.
squared = {n: n**2 for n in range(1, 6)}# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Sets — unique elements and set algebra
Section titled “Sets — unique elements and set algebra”A set is an unordered collection of unique hashable elements.
It is optimised for in membership tests (O(1) average) and supports mathematical set operations.
a = {1, 2, 3, 4}b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}print(a & b) # intersection: {3, 4}print(a - b) # difference: {1, 2}print(a ^ b) # symmetric diff: {1, 2, 5, 6}Use frozenset for an immutable set (hashable, usable as a dict key or set element).
Full runnable demo
Section titled “Full runnable demo”# --- dict safe access ---scores = {'alice': 95, 'bob': 87}scores['carol'] = 92print('scores:', scores)
unknown = scores.get('dave', 0)print('dave score:', unknown)
scores.setdefault('eve', 88)print('after setdefault:', scores)
for name, score in scores.items(): print(f' {name}: {score}')
# --- dict comprehension ---squared = {n: n**2 for n in range(1, 6)}print('squared:', squared)
# --- set algebra ---a = {1, 2, 3, 4}b = {3, 4, 5, 6}print('union:', sorted(a | b))print('intersection:', sorted(a & b))print('difference:', sorted(a - b))print('symmetric diff:', sorted(a ^ b))Loading Python runtime (first run only)…