Dictionaries & Sets

8. Dictionaries & Sets#

import sys
from pathlib import Path

# Find project root by looking for _config.yml
current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent
        break
else:
    project_root = Path.cwd().parent.parent

# Add project root to path
sys.path.insert(0, str(project_root))

# Import shared teaching helpers and cell magics
from shared import thinkpython, diagram, jupyturtle, structshape
from shared.download import download

This chapter introduces two of Python’s most powerful built-in data structures: dictionaries and sets.

Dictionaries map keys to values, giving you fast lookup by name rather than by position. They are the foundation of many elegant algorithms — from counting word frequencies to building indexes and caches.

Sets store unordered collections of unique elements. They support efficient membership testing and the classic mathematical operations — union, intersection, and difference — making them ideal for problems like deduplication and finding common elements.

Topics covered in this chapter:

Data Structure

Topic

Description

Dict

Dictionary basics

Creating, accessing, and modifying key-value pairs

Dictionary methods

.keys(), .values(), .items(), .get(), .update(), and more

Dictionary comprehensions

Building dictionaries concisely with a single expression

Counting & histograms

Using dictionaries to tally occurrences

Set

Set basics

Creating sets and understanding unordered uniqueness

Set operations

Union (|), intersection (&), difference (-), symmetric difference (^)

Set comprehensions

Building sets concisely with a single expression

Both

Choosing the right structure

When to use a list, dict, or set