Skip to content

Dicts and Sets

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 key
print(scores['alice']) # 95
del scores['bob'] # remove a key
print(scores) # {'alice': 95, 'carol': 92}

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 KeyError
scores.setdefault('eve', 88) # inserts eve=88 only if absent
print(scores)
# {'alice': 95, 'bob': 87, 'eve': 88}

.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.

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}

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).

# --- dict safe access ---
scores = {'alice': 95, 'bob': 87}
scores['carol'] = 92
print('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))
What does `scores.get('dave', 0)` return when 'dave' is not in the dict?
What does `scores.setdefault('eve', 88)` do when 'eve' is already in scores?
Which set operation returns elements that are in BOTH sets?
How do you create an empty set in Python?