Python · Chapter 5 of 21
Python dictionaries and sets: lookups, grouping and counting
14 min study · Examples checked with Python 3.14 and 3.15 ·
Lists are good at “what comes next?”. Many questions are different: what is the email of learner 42, how many people chose each course, which learners are in both groups? Dictionaries answer the first two kinds of question, by mapping keys to values. Sets answer the third, by storing unique items and comparing groups. This chapter works through a small list of enrollment records with both.
Create, read and update a dictionary
A dictionary maps keys to values. Each key appears once; assigning to an existing key replaces its value.
learner = {"name": "Ada", "course": "Python", "completed": 3}
print(learner["name"]) # Ada
print(learner.get("timezone", "UTC")) # UTC
learner["completed"] += 1
learner.update(course="Django", active=True)
print(learner)
# {'name': 'Ada', 'course': 'Django', 'completed': 4, 'active': True}
print(len(learner), "active" in learner) # 4 True
for key, value in learner.items():
print(f"{key:>9}: {value}")
Reading a missing key with square brackets raises a KeyError. get returns a default instead (or None if you give none) and leaves the dictionary unchanged. Use square brackets for keys that must exist, so that a missing one fails loudly, and get for keys that are optional by design. A default in the wrong place hides bugs: the program keeps going with “UTC” when the real problem is that the timezone was never loaded.
Dictionaries remember insertion order, and updating a value keeps the key in its place. Looping over a dictionary gives its keys; .values() gives the values and .items() gives key-value pairs. These three are live views: if the dictionary changes, the view shows the change. Never add or remove keys while looping over a dictionary, because Python raises a RuntimeError; loop over list(d) instead, or build a new dictionary.
What can be a key
Keys must be hashable, which in practice means immutable: strings, numbers, booleans, None, and tuples made of those. A list cannot be a key, since its contents, and therefore its hash, could change after it was stored. Tuples make natural composite keys:
seats = {("Python", "2026-12"): 30, ("Django", "2026-12"): 20}
print(seats[("Python", "2026-12")]) # 30
try:
seats[["Python", "2027-01"]] = 25
except TypeError as error:
print(error) # cannot use 'list' as a dict key (unhashable type: 'list')
Values have no restrictions; a value can be a list, another dictionary or any object. Nested dictionaries and lists are how JSON data looks once loaded into Python (chapter 15).
Missing key, or a stored None?
get returns the same default for “the key is absent” and “the key holds None”. When the difference matters, test with in, or use a sentinel: a unique object that no stored value can equal.
settings = {"limit": 0, "note": None}
print("note" in settings, "theme" in settings) # True False
print(settings.get("limit", 10)) # 0
MISSING = object()
note = settings.get("note", MISSING)
if note is MISSING:
print("no note key")
elif note is None:
print("note is explicitly empty") # note is explicitly empty
Note that get("limit", 10) correctly returns the stored 0; the default applies only to absent keys. Python 3.15 adds a built-in sentinel type for this pattern, so MISSING = sentinel("MISSING") gives the marker a readable name in error messages. The object() version works in every version.
To remove keys, pop(key, default) returns the removed value or the default, while del d[key] raises KeyError for a missing key.
Group and count records
A common job is turning a flat list of records into groups. setdefault returns the value for a key, first inserting a default if the key is missing, which makes grouping a one-liner per record:
records = [
("Ada", "Python"), ("Grace", "Django"),
("Ada", "FastAPI"), ("Linus", "Python"),
]
courses_by_learner = {}
for name, course in records:
courses_by_learner.setdefault(name, []).append(course)
print(courses_by_learner["Ada"]) # ['Python', 'FastAPI']
lookup = {name: course for name, course in records}
print(lookup["Ada"]) # FastAPI (the first course was overwritten)
The dictionary comprehension in the last lines shows what goes wrong without grouping: the second record for Ada replaces the first. Decide for each data set whether a repeated key should overwrite, accumulate or count as an error.
The collections module has two classes built for these jobs:
from collections import Counter, defaultdict
records = [("Ada", "Python"), ("Grace", "Django"), ("Ada", "FastAPI"), ("Linus", "Python")]
enrolments = Counter(course for _, course in records)
print(enrolments["Python"], enrolments["Rust"]) # 2 0
print(enrolments.most_common(1)) # [('Python', 2)]
by_course = defaultdict(list)
for name, course in records:
by_course[course].append(name)
print(dict(by_course))
# {'Python': ['Ada', 'Linus'], 'Django': ['Grace'], 'FastAPI': ['Ada']}
A Counter counts hashable items and returns 0 for anything it has not seen. A defaultdict(list) creates an empty list the first time a key is used. Be aware that with a defaultdict, merely reading a missing key inserts it.
Merge and transform dictionaries
The | operator merges two dictionaries into a new one, with the right-hand side winning on shared keys; |= updates in place. Comprehensions filter and transform:
progress = {"Ada": 4, "Grace": 2, "Linus": 0}
merged = progress | {"Grace": 3, "Joan": 1}
active = {name: n for name, n in progress.items() if n > 0}
ranking = sorted(progress.items(), key=lambda item: item[1], reverse=True)
print(merged) # {'Ada': 4, 'Grace': 3, 'Linus': 0, 'Joan': 1}
print(active) # {'Ada': 4, 'Grace': 2}
print(ranking[0]) # ('Ada', 4)
Sorting a dictionary by its values means sorting its items, as in the ranking line. Python 3.15 also has a built-in immutable mapping, frozendict, which can be hashed and used as a key or a constant table; a normal dict remains the right choice for data that changes.
Sets: unique items and group comparisons
A set holds unique, hashable items with no order. Converting a list to a set removes duplicates, and membership tests stay fast however large the set gets.
python_group = {"Ada", "Linus", "Grace"}
web_group = {"Ada", "Joan"}
print(sorted(python_group & web_group)) # ['Ada']
print(sorted(python_group | web_group)) # ['Ada', 'Grace', 'Joan', 'Linus']
print(sorted(python_group - web_group)) # ['Grace', 'Linus']
print(sorted(python_group ^ web_group)) # ['Grace', 'Joan', 'Linus']
python_group.add("Joan")
python_group.discard("Nobody") # no error if absent
print(web_group <= python_group) # True
print(len({"a", "b", "a"}), set()) # 2 set()
& gives items in both sets, | items in either, - items in the left set only, and ^ items in exactly one. <= asks whether one set is a subset of another. remove raises a KeyError for a missing item; discard doesn’t. Write an empty set as set(), since {} is an empty dictionary. Sets print in an arbitrary order, so sort them when output must be stable, as above. A frozenset is the immutable version and can itself be a dictionary key or a member of another set.
Converting a list to a set costs time, so when you check membership repeatedly inside a loop, build the set once before the loop. And if order or duplicates matter for something else, keep the original list too.
Practice
Using the records list from this chapter, print how many learners each course has, list every learner’s courses, and print the learners who take Python and at least one web framework (Django or FastAPI).
Answer check: Python has 2 learners, Django and FastAPI one each. Ada’s courses are ['Python', 'FastAPI']. Build one set of Python learners and one of web-framework learners; their intersection is {'Ada'}.
Summary
Use a dictionary to look values up by key, square brackets for required keys and get for optional ones. Keys must be hashable. Group with setdefault or defaultdict, count with Counter, and decide what a repeated key should mean. Sets remove duplicates and compare groups with &, |, - and ^.