Dictionaries and Sets
Use mappings for keyed lookup and sets for unique membership and set algebra.
Dictionaries associate unique keys with values. Sets store unique values without positional indexing. Both use hashing, so membership is typically fast.
Dictionaries: key-to-value mappings
profile = {
"name": "Ada",
"language": "Python",
"active": True,
}
print(profile["name"]) # Ada
profile["city"] = "London"
profile["active"] = FalseKeys must be hashable: strings, numbers, and tuples of hashable values are common choices. Lists, dictionaries, and sets cannot be keys.
Dictionary insertion order is preserved, but access should normally express meaning through keys rather than positions.
Safe lookup and updates
Bracket lookup raises KeyError for a missing key. get returns a default:
print(profile.get("timezone")) # None
print(profile.get("timezone", "UTC")) # UTCUse brackets when absence is a data error. Use get when a fallback is part of the design.
inventory = {"pens": 10}
inventory["pens"] += 5
inventory.setdefault("notebooks", 0)
removed = inventory.pop("pens")setdefault inserts its default only when the key is absent, but explicit logic is often easier
to read for complex updates.
Merge mappings with | in modern Python:
defaults = {"theme": "light", "page_size": 20}
preferences = {"theme": "dark"}
settings = defaults | preferences
print(settings) # {'theme': 'dark', 'page_size': 20}Keys on the right win. update and |= mutate an existing dictionary.
Iterating over dictionaries
prices = {"pen": 1.5, "book": 8.0}
for product in prices:
print(product) # keys
for product, price in prices.items():
print(f"{product}: ${price:.2f}")
print(list(prices.keys()))
print(list(prices.values()))The views returned by keys, values, and items reflect later dictionary changes.
Dictionary comprehensions
words = ["python", "loop", "mapping"]
lengths = {word: len(word) for word in words}
print(lengths)Use a loop instead when the transformation needs several statements or error handling.
Sets: unique, unordered membership
tags = {"python", "beginner", "python"}
print(tags) # duplicate removed; display order is not guaranteed
tags.add("functions")
tags.discard("missing") # no error
tags.remove("beginner") # KeyError if absentAn empty set is set(). {} creates an empty dictionary.
Set algebra expresses relationships directly:
required = {"python", "git", "sql"}
known = {"python", "html", "git"}
print(required & known) # intersection: known requirements
print(required | known) # union: all skills
print(required - known) # difference: missing skills
print(required ^ known) # symmetric difference: in exactly one
print({"python"} <= known) # subsetUse frozenset for an immutable, hashable set:
permissions = frozenset({"read", "write"})Deduplication and order
set(values) removes duplicates but does not preserve a meaningful sequence order. If first
occurrence order matters, dictionary keys provide a concise approach:
names = ["Ada", "Grace", "Ada", "Guido"]
unique_in_order = list(dict.fromkeys(names))
print(unique_in_order) # ['Ada', 'Grace', 'Guido']Choosing list, tuple, dictionary, or set
- List: ordered sequence, duplicates allowed, collection changes.
- Tuple: ordered fixed-shape value, positions have stable meaning.
- Dictionary: each value is addressed by a unique meaningful key.
- Set: unique values, membership and set operations matter, order does not.
Ask what operation defines the data:
- “Give me the third item” suggests a sequence.
- “Give me the price for this product ID” suggests a dictionary.
- “Have I seen this ID?” suggests a set.
- “This coordinate always has two parts” suggests a tuple.
Convert between types deliberately at boundaries rather than using one structure for every task.
Common mistakes
- Using
{}for an empty set. - Expecting a stable set iteration order.
- Accessing a missing dictionary key without deciding how absence should behave.
- Testing a dictionary for a value with
value in mapping; membership checks keys. - Mutating a dictionary or set's size while iterating over it.
- Using a mutable object as a key or set element.
- Using
get(key) or defaultwhen stored falsy values such as0are valid.
Decision guidance
- Prefer bracket lookup when a key is required and failure should be visible.
- Prefer
getwhen missing data has a legitimate default. - Use a set for repeated membership checks, uniqueness, and comparisons between groups.
- Preserve order explicitly with a list or dictionary; never depend on set display order.
- If records have many fixed fields and behavior, move beyond raw dictionaries to a data class.
Practice
- Count words in a sentence with a dictionary.
- Find shared and missing course topics using set operations.
- Deduplicate a list while preserving first occurrence order.
- Build a product-price dictionary and print each pair using
.items().
LEARNING RECORD
Finish this lesson
Mark it complete when you can explain the main decision without looking.
KNOWLEDGE CHECK