Chapter 7

Dictionaries

7.1 Dictionaries · 7.2 Core Operations · 7.3 Dictionary Patterns · 7.4 Sets

← → or Space to navigate · F for fullscreen

7.1 Dictionaries

Key-value mappings — the workhorse of Python data

What Is a Dictionary?

A dictionary stores data as key–value pairs.

  • Look up a key → get its value
  • Keys must be unique and hashable
  • Values can be any type
person = {"name": "Alice", "age": 28}
config = {"debug": True, "timeout": 30}
word_count = {}          # empty dict

When to use a dict

  • You need labeled data (vs positional)
  • You want fast lookups by name
  • You need a mapping relationship
Use case Example
Student records {"id": 42, "gpa": 3.8}
Config settings {"theme": "dark"}
Word counts {"the": 12, "cat": 3}
JSON data any API response

Creating Dictionaries

Dict literal

scores = {"alice": 92, "bob": 85}

dict() constructor

# from keyword arguments
d = dict(name="Alice", age=28)

# from list of (key, value) pairs
pairs = [("a", 1), ("b", 2)]
d = dict(pairs)

dict.fromkeys()

# all keys share the same default value
keys = ["x", "y", "z"]
d = dict.fromkeys(keys, 0)
# {"x": 0, "y": 0, "z": 0}

Dict comprehension

squares = {x: x**2 for x in range(6)}
# {0:0, 1:1, 2:4, 3:9, 4:16, 5:25}

Keys must be hashable — str, int, and float work; a tuple works only when every element is hashable. list and dict do not.

Nesting

students = {
    "alice": {"gpa": 3.9, "year": 2},
    "bob":   {"gpa": 3.4, "year": 3},
}
print(students["alice"]["gpa"])   # 3.9

7.2 Core Operations

Accessing, modifying, and querying dictionaries

Accessing Items

Square-bracket access

person = {"name": "Alice", "age": 28}

print(person["name"])      # Alice
# person["email"]          # KeyError!

Optional fields with .get()

# returns None if key missing
print(person.get("email"))        # None

# returns default if key missing
print(person.get("email", "N/A")) # N/A

Membership testing

"name" in person      # True
"email" in person     # False
"email" not in person # True

Choose by meaning: d[key] reveals missing required data; d.get(key, default) handles expected absence without inserting; d.setdefault(key, default) creates a missing entry. An existing value of None is not replaced by a fallback.

Lists and Dictionaries: Access and Mutation

Lists use positions; dictionaries use keys.

Operation List nums Dictionary d
Read nums[i] d[key]
Read with fallback No get() equivalent d.get(key, default)
Replace nums[i] = value (existing index) d[key] = value (add or replace)
Add nums.append(value) or nums.insert(i, value) d[key] = value (new key)
Delete, no return del nums[i] or del nums[i:j] del d[key]

Invalid indices raise IndexError; missing keys raise KeyError when no fallback is supplied.

Lists and Dictionaries: Removal and Inspection

Operation List nums Dictionary d
Remove by value nums.remove(value) removes first match No remove(); deletion uses keys
Remove and return nums.pop(i); no fallback d.pop(key, default)
Remove last nums.pop() returns an element d.popitem() returns (key, value)
Clear nums.clear() d.clear()
Membership value in nums key in d; value in d.values()
Iterate for value in nums for key in d; for key, value in d.items()
Count len(nums) len(d)

Adding, Updating, and Deleting

Add / update

person["email"] = "alice@example.com"  # add
person["age"] = 29                     # update

# update multiple keys at once
person.update({"age": 30, "city": "Rolla"})

Delete

del person["city"]           # statement, no return
email = person.pop("email")  # remove, return value
phone = person.pop("phone", "N/A")  # default if missing
last = person.popitem()      # remove last inserted pair

del also removes list elements, slices, and variable bindings. It does not return a value.

Dictionary pop(key, default) uses a key and an optional fallback. List pop(index) uses an optional index and has no fallback. Without a fallback, a missing dictionary key raises KeyError. Like list pop(), d.popitem() removes the last item, but returns a (key, value) tuple.

Useful inspection methods

person.keys()    # dict_keys([...])
person.values()  # dict_values([...])
person.items()   # dict_items([(k,v), ...])
len(person)      # number of key-value pairs

dict.keys(), .values(), and .items() return view objects — they reflect changes to the dict in real time.

7.3 Dictionary Patterns

Transform data, count and group observations, model records

Transforming Dictionary Data

Iterate before writing a comprehension. Dictionary iteration follows insertion order; use sorted() for sorted presentation.

prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}
for fruit, price in prices.items():
    print(fruit, price)

discounted = {fruit: round(price * 0.9, 2)
              for fruit, price in prices.items()}
pricey = {fruit: price for fruit, price in prices.items()
          if price > 1.00}
Result needed Iteration
Keys for key in d
Values for value in d.values()
Pairs for key, value in d.items()

Views reflect later changes. list(d) is a snapshot of keys. Avoid adding or removing keys during iteration.

Counting and Grouping Observations

from collections import Counter, defaultdict

observations = ["apple", "banana", "apple"]
counts = {}
for fruit in observations:
    counts[fruit] = counts.get(fruit, 0) + 1
print(counts)  # {'apple': 2, 'banana': 1}
print(Counter(observations).most_common(1))  # [('apple', 2)]

records = [("Ana", "CS101"), ("Ben", "CS101"), ("Ana", "DS201")]
courses = defaultdict(list)
for name, course in records:
    courses[name].append(course)

Counting: category → number. Grouping: category → list.

Use the manual loop to understand the pattern; use Counter for tallying and defaultdict(list) for grouping.

Choose Missing-Key Behavior

Operation Missing key Inserts?
d[key] (regular dict) KeyError No
d.get(key, default) Returns fallback No
d.setdefault(key, default) Stores and returns fallback Yes
dd[key] (defaultdict with factory) Creates factory value Yes
dd.get(key) None No
from collections import defaultdict

groups = defaultdict(list)
print(groups.get("north"))  # None
print(dict(groups))         # {}
print(groups["north"])     # []
print(dict(groups))         # {'north': []}

Required data can use brackets; optional data can use get(). Grouping creates containers as needed.

Inversion and Sorted Summaries

New keys must be hashable. A direct swap also requires unique original values if every association must survive.

grades = {"Ana": "A", "Ben": "B", "Chen": "A"}
# Loses Ana because the new key "A" appears twice:
print({grade: name for name, grade in grades.items()})

by_grade = {}
for name, grade in grades.items():
    by_grade.setdefault(grade, []).append(name)
print(by_grade)  # {'A': ['Ana', 'Chen'], 'B': ['Ben']}
def second_element(pair):
    return pair[1]

counts = {"i": 4, "s": 4, "m": 1}
print(sorted(counts.items(), key=second_element))
print(max(counts.items(), key=second_element))  # ('i', 4)

Sorting is stable. max() returns the first maximal item encountered; state the tie policy.

Modeling Records and Compound Keys

Lookup needed Key Value
One student's record Student ID Nested dictionary
All grades for one student Student name Subject-to-score dictionary
One score by two fields (name, subject) Numeric score
student = {"name": "Ana", "grades": {"math": 91}}
print(student["grades"]["math"])
student["grades"].update({"science": 84})
student.setdefault("contact", {})["city"] = "Austin"

scores = {("Ana", "math"): 91, ("Ana", "science"): 84}
for (name, subject), score in scores.items():
    print(name, subject, score)

Hashable: stable hash, equal objects have equal hashes. Tuples work only when all elements are hashable. Lists, dicts, and sets cannot be keys.

Shallow Copies and Shared Defaults

Assignment shares the outer dictionary; a shallow copy creates a new outer dictionary but can share inner objects.

Construction Outer dictionary Inner grades dictionary
alias = student Shared Shared
copy = student.copy() Separate Shared
Also copy student["grades"] Separate Separate
student = {"grades": {"math": 91}}
copy_of_student = student.copy()
copy_of_student["grades"]["math"] = 95
print(student["grades"])  # {'math': 95}
student ────────────┐
                    ├── shared grades dictionary
copy_of_student ────┘

Shared Defaults in fromkeys

Each key receives the same supplied value object. A comprehension creates a new list per key.

names = ["Ana", "Ben"]
shared = dict.fromkeys(names, [])
shared["Ana"].append(91)
print(shared)  # {'Ana': [91], 'Ben': [91]}

separate = {name: [] for name in names}

Predict the effect, run the example, then repair the construction.

Accumulate and Filter a Report

stock = {"apple": 15, "banana": 4, "cherry": 0}
total = 0
low_stock = []
for fruit, units in stock.items():
    total += units
    if units < 10:
        low_stock.append(fruit)
print(total)      # 19
print(low_stock)  # ['banana', 'cherry']
Task Result
Accumulate units Running numeric total
Filter fruit names List of matching keys
Filter key-value pairs New dictionary comprehension

The input and output do not need to have the same collection type.

Lookup Performance

Operation Growth with entry count
List membership O(n) worst case
List indexing O(1)
Dictionary key lookup Average O(1), worst case O(n)
Set membership Average O(1), worst case O(n)

Repeat lookups at several sizes using timeit.repeat(). Construct the collection outside the measured operation. Section 7.4 compares all three collections and measures set construction separately.

Consider the whole task: building a lookup collection costs time and memory. Reuse it for repeated searches. For membership alone, a set expresses the intent directly.

Optional Review: Dictionaries as Memory

A memo maps an argument to an already computed result. The plain Fibonacci call graph repeats subproblems:

                 fib(4)
              /          \
          fib(3)         fib(2)
         /     \         /    \
      fib(2) fib(1)   fib(1) fib(0)
      /    \
   fib(1) fib(0)
known = {0: 0, 1: 1}
def fibonacci_memo(n):
    if n not in known:
        known[n] = fibonacci_memo(n - 1) + fibonacci_memo(n - 2)
    return known[n]

Reset the cache to measure a first computation. A second call measures cached retrieval. See the full call graph and Lucas exercise in the notebook.

7.4 Sets

Unordered collections of unique, hashable elements

Creating Sets and Membership

Create

a = {1, 2, 3}
b = set([3, 4, 5])    # from list
empty = set()          # NOT {} (that's a dict)

# duplicates removed automatically
s = {1, 2, 2, 3, 3}   # {1, 2, 3}

No indexing — iterate or test membership

3 in a      # True   O(1)
6 not in a  # True

for item in a:
    print(item)    # order not guaranteed

When to use a set

Need Use
Ordered, duplicates OK list
Fixed structure, hashable tuple
Unique elements, fast lookup set
Key-value mapping dict

Sets are great for deduplication and membership testing. x in set is O(1); x in list is O(n).

Set Algebra: Membership Rules

For a = {1, 2, 3} and b = {3, 4, 5}, predict each result before running it.

Region Elements Union Intersection a - b Symmetric difference
Only a 1, 2 Keep Omit Keep Keep
Both 3 Keep Keep Omit Omit
Only b 4, 5 Keep Omit Omit Keep

Difference has a direction: a - b and b - a select different regions. Algebra operations create new sets; update methods change the original.

Set Algebra and Mutation

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
Operation Operator Method
Union a | b a.union(b)
Intersection a & b a.intersection(b)
Difference a - b a.difference(b)
Sym. difference a ^ b a.symmetric_difference(b)
a | b   # {1, 2, 3, 4, 5, 6}
a & b   # {3, 4}
a - b   # {1, 2}
a ^ b   # {1, 2, 5, 6}

Modify in place

a.add(5)          # add one element
a.update({6, 7})  # add multiple

a.remove(1)       # KeyError if missing
a.discard(99)     # safe — no error
a.pop()           # remove arbitrary element

Subset / superset

{1, 2} <= {1, 2, 3}   # True  (subset)
{1, 2, 3} >= {1, 2}   # True  (superset)

Frozensets, Hashability, and Performance

frozenset — immutable set

fs = frozenset({1, 2, 3})
# fs.add(4)   ← AttributeError

# Can be a dict key or set element
graph = {frozenset({1, 2}): "edge A"}
set frozenset
Mutable ✓ ✗
Hashable ✗ ✓
Dict key ✗ ✓

Set comprehension

# unique squares of even numbers
s = {x**2 for x in range(10) if x % 2 == 0}
# {0, 4, 16, 36, 64}

# deduplicate a list
words = ["the", "cat", "the", "mat"]
unique = {w.lower() for w in words}

O(1) membership — why it matters

# set membership is O(1) vs O(n) for list
big = set(range(1_000_000))
999_999 in big   # average O(1) membership

Chapter 7 — Quick Reference

Concept Key syntax / notes
Create {"k": v} · dict(k=v) · dict.fromkeys(keys, 0)
Access d[key] (KeyError if missing) · d.get(key, default) (safe)
Add / update d[key] = val · d.update({...})
Delete del d[key] · d.pop(key) · d.popitem()
Membership key in d — O(1)
Iterate d.keys() · d.values() · d.items()
Comprehension {k: v for k, v in iterable}
Count Counter(seq) → .most_common(n)
Group defaultdict(list) — no KeyError on first access
Invert {v: k for k, v in d.items()}
Memoize Store previous results in a dict to avoid repeated work
Sets {1, 2} · set() for an empty set · s.add(x) · s.discard(x)
Set algebra a | b · a & b · a - b · a ^ b
Deduplicate list(set(lst))

End of Chapter 7

Next: Chapter 8 — Strings

string methods · regex · text analysis · word frequencies