Dictionaries & Sets
Chapter 7 ended on a problem: a record like ["Priya", 91] only makes sense if you already remember that position 0 is a name and position 1 is a score. Dictionaries fix that by naming each field instead of numbering it. Sets solve a different, equally common problem — keeping a collection where every value is guaranteed unique. Both are everywhere in real software, and this chapter is where you start using them.
How to read this chapter
- Start with the pattern. Each section teaches one small dictionary or set idea at a time.
- Read the example first. The code mirrors real situations like student records, inventories, and survey tallies.
- Try one line at a time. The playgrounds are meant for quick experiments, not long typing.
1. Creating dictionaries & accessing values
- Dictionary = a collection of
key: valuepairs, instead of numbered positions. - You look up a value by its key, not by an index number.
- A missing key crashes unless you check for it first.
"age", not the box at position 1.
key: value
pairs, written between curly braces:
student = {"name": "Priya", "age": 22}. Every key is
unique and works like a label — you fetch a value by its key,
student["name"], instead of by position.
student = {"name": "Priya", "age": 22, "major": "CS"}
print(student)
print(len(student)) # 3 — same len() you already know from lists
A dictionary's shape is different from a list's — every value has a name attached to it, and that name is what you use to fetch it back:
student = {"name": "Priya", "age": 22, "major": "CS"}
key -> value
"name" -> "Priya"
"age" -> 22
"major" -> "CS"
student = {"name": "Priya", "age": 22, "major": "CS"}
print(student["name"]) # 'Priya'
print(student["major"]) # 'CS'
Reaching for a key that doesn't exist doesn't return an empty value — it crashes immediately, the same way an out-of-range list index does:
student = {"name": "Priya", "age": 22, "major": "CS"}
print(student["gpa"])
# KeyError: 'gpa'
KeyError is what Python raises when you index a
dictionary with a key that isn't there. It's the dictionary
equivalent of an IndexError on a list — both mean
"that spot doesn't exist."
.get() avoids the crash entirely — it returns
None for a missing key instead of raising an error, and
you can hand it a fallback value to use instead of None:
student = {"name": "Priya", "age": 22, "major": "CS"}
print(student.get("gpa")) # None — no crash
print(student.get("gpa", "N/A")) # 'N/A' — your own fallback instead
The in keyword you already know from strings and lists
works the same way here — it checks whether a value is a
key in the dictionary, before you ever try to
access it:
student = {"name": "Priya", "age": 22, "major": "CS"}
print("major" in student) # True
print("gpa" in student) # False
if "gpa" in student:
print(student["gpa"])
else:
print("No GPA on file")
Go Deeper: what can be a dictionary key?
Keys are almost always strings or numbers in everyday code, but Python actually allows any immutable value as a key — a number, a string, or a tuple (Chapter 7). Lists can't be keys, because keys need to stay fixed for lookups to work reliably; this is one of the few places tuples earn their keep over lists in practice.
- A dictionary is written with curly braces as
{key: value, ...}, and values are fetched by key, not position. - A missing key raises
KeyError;.get(key, default)avoids the crash and returns a fallback instead. "key" in some_dictchecks for a key's existence before you risk accessing it.
2. Dictionary methods that add, update, and remove
.update()adds or overwrites several keys at once..pop(),.setdefault(), anddelremove or safely insert entries..keys(),.values(),.items()hand back views of a dictionary's parts.
Setting a new key works exactly like overwriting an existing one —
just assign to it with square brackets. .update()
instead merges in several keys at once from another dictionary:
inventory = {"apples": 50, "bananas": 30}
inventory["cherries"] = 20 # add a brand-new key
print(inventory) # {'apples': 50, 'bananas': 30, 'cherries': 20}
inventory.update({"bananas": 45, "dates": 15})
print(inventory) # {'apples': 50, 'bananas': 45, 'cherries': 20, 'dates': 15}
.update(other_dict) merges another dictionary's keys in:
new keys get added, and any key that already exists gets its value
overwritten. It's the dictionary version of .extend() on
a list — several changes in one call instead of one at a time.
Removing an entry works three different ways, depending on what you need back:
.pop(key)removeskeyand returns its value.del some_dict[key]removeskeywithout returning anything..setdefault(key, default)is the safe opposite of removing — it insertskeyonly if it's missing, and never overwrites an existing value.
inventory = {"apples": 50, "bananas": 45, "cherries": 20, "dates": 15}
removed = inventory.pop("apples")
print(removed, inventory) # 50 {'bananas': 45, 'cherries': 20, 'dates': 15}
del inventory["dates"]
print(inventory) # {'bananas': 45, 'cherries': 20}
inventory.setdefault("elderberries", 0) # not present -> inserted
inventory.setdefault("bananas", 999) # already present -> unchanged
print(inventory) # {'bananas': 45, 'cherries': 20, 'elderberries': 0}
Three more methods hand back the dictionary's parts, which is
especially useful for looping (Section 3): .keys(),
.values(), and .items() — the last one
gives you key-value pairs together:
inventory = {"bananas": 45, "cherries": 20, "elderberries": 0}
print(list(inventory.keys())) # ['bananas', 'cherries', 'elderberries']
print(list(inventory.values())) # [45, 20, 0]
print(list(inventory.items())) # [('bananas', 45), ('cherries', 20), ('elderberries', 0)]
.items() returns every key-value pair as a tuple
(Chapter 7) — ("bananas", 45) — bundled into one view
you can loop over. Wrapping any of these three methods in
list(...) is only needed to print them nicely; looping
directly over .items() (next section) never needs it.
Go Deeper: .pop() with a default, just like .get()
.pop(key) crashes with a KeyError if
key isn't present — same risk as student["gpa"]
from Section 1. Just like .get(),
.pop(key, default) accepts a second argument: a
fallback value returned instead of crashing when the key is
missing. Reach for it any time you want to remove-if-present
without an if "key" in dict check first.
some_dict[key] = valueadds or overwrites one entry;.update()merges in several at once..pop(key)removes and returns a value;del some_dict[key]removes without returning;.setdefault()inserts only if missing..keys(),.values(), and.items()hand back views of a dictionary's keys, values, or key-value pairs.
3. Looping over dictionaries
for key in some_dict:loops over keys only.for key, value in some_dict.items():loops over both at once.- Since Python 3.7, a dictionary always remembers its insertion order.
.items() whenever a loop needs both the key and the value.
A plain for loop over a dictionary walks its
keys, one at a time — this is the same
for loop from Chapter 5, just handed a dictionary
instead of a list:
scores = {"Priya": 91, "Amir": 84, "Zoe": 77}
for name in scores:
print(name)
# Priya
# Amir
# Zoe
That's fine when you only need the names, but most real loops need
the value too — which means indexing back in with
scores[name] on every pass. .items()
avoids that extra step by handing over both parts directly:
scores = {"Priya": 91, "Amir": 84, "Zoe": 77}
for name, score in scores.items():
print(name, "-", score)
# Priya - 91
# Amir - 84
# Zoe - 77
scores reliably visits
Priya, then Amir, then Zoe, in that order, every single time.
That predictability makes the accumulator pattern from Chapter 5 work just as well on dictionaries as it did on lists — loop, check a condition, and build up a running result:
scores = {"Priya": 91, "Amir": 84, "Zoe": 77}
total = 0
passing = 0
for name, score in scores.items():
total = total + score
if score >= 80:
passing += 1
print(name, "passed with", score)
print("Average:", total / len(scores))
print("Passing count:", passing)
Go Deeper: looping over .keys() or .values() directly
for name in scores: and
for name in scores.keys(): do exactly the same
thing — plain iteration over a dictionary already walks its keys,
so .keys() is optional and mostly used for
readability. for score in scores.values(): is the
one-sided version when you only need the values and don't care
which name they belong to.
for key in some_dict:loops over keys only; index back in withsome_dict[key]if you need the value too.for key, value in some_dict.items():gives you both in one pass — the most common loop shape.- Dictionaries preserve insertion order, so the same loop visits entries in the same order every time.
4. Sets: unique collections & set operations
- Set = an unordered collection with no duplicate values, ever.
.add()and.remove()change a set;inchecks membership.|,&, and-combine two sets: union, intersection, difference.
: value part:
team = {"Priya", "Amir", "Zoe"}. Adding a duplicate does
nothing — a set can never hold the same value twice, and it doesn't
remember insertion order the way a dictionary does.
team_a = {"Priya", "Amir", "Zoe"}
print(team_a) # some order — sets don't preserve insertion order
print(len(team_a)) # 3
duplicates = {"a", "b", "a", "c", "b"}
print(duplicates) # only 3 unique values ever get stored
print(len(duplicates)) # 3, not 5
Because a set has no positions, there's no indexing and no
.append() — instead, .add() inserts one
value and .remove() takes one out:
team_a = {"Priya", "Amir", "Zoe"}
team_a.add("Leo")
print("Leo" in team_a) # True
print(len(team_a)) # 4
team_a.remove("Leo")
print("Leo" in team_a) # False
print(len(team_a)) # 3
That last line is the real reason sets are useful: checking
value in some_set is how you ask "have I already seen
this?" — the same in keyword from Chapters 6-8, just
answering that question far faster than checking a long list one
item at a time.
The three set operators are where sets really earn their keep — each one answers a different question about two sets at once:
a | b— union: everyone ina,b, or both.a & b— intersection: only what's in bothaandb.a - b— difference: what's inabut not inb.
team_a = {"Priya", "Amir", "Zoe"} team_b = {"Zoe", "Sam", "Bo"}
team_a only both team_b only
----------- ------ -----------
Priya, Amir Zoe Sam, Bo
team_a | team_b (union) -> Priya, Amir, Zoe, Sam, Bo
team_a & team_b (intersection) -> Zoe
team_a - team_b (difference) -> Priya, Amir
team_a = {"Priya", "Amir", "Zoe"}
team_b = {"Zoe", "Sam", "Bo"}
print("Zoe" in (team_a & team_b)) # True — Zoe is on both teams
print(len(team_a | team_b)) # 5 — total unique people
print("Priya" in (team_a - team_b)) # True — Priya is only on team_a
Go Deeper: turning a list into a set
Wrapping any list in set(...) — set(some_list)
— instantly gives you the unique values from that list, dropping
every duplicate. This is one of the most common one-line uses of
a set in real code, and shows up again in Section 6's
deduplication example.
- A set holds unique values with curly braces and no
: valuepart; duplicates are silently dropped. .add()and.remove()change a set;value in some_setchecks membership.|(union),&(intersection), and-(difference) combine two sets in three different ways.
5. Nested dictionaries & real-world records
- Nested dictionary = a dictionary whose values are themselves dictionaries.
- Two keys reach a single value: outer key, then inner key.
- Combines naturally with Chapter 7's lists — a dict of lists, or a list of dicts.
students = {
"Priya": {"age": 22, "major": "CS"},
"Amir": {"age": 24, "major": "Math"},
}
print(students["Priya"]) # {'age': 22, 'major': 'CS'} — the whole inner dict
print(students["Priya"]["major"]) # 'CS' — reach in with a second key
The first key picks a student's record; the second key picks one field inside that record. Updating a nested dictionary works the same way — reach in with both keys, then assign:
students = {
"Priya": {"age": 22, "major": "CS"},
"Amir": {"age": 24, "major": "Math"},
}
students["Priya"]["age"] = 23
print(students["Priya"]) # {'age': 23, 'major': 'CS'}
Dictionaries and lists combine naturally in two directions. A dictionary can map a name to a list of values — a class roster mapping each course to its list of enrolled students:
roster = {
"CS101": ["Priya", "Zoe"],
"MATH200": ["Amir"],
}
roster["CS101"].append("Sam") # the value is a list, so list methods work
print(roster) # {'CS101': ['Priya', 'Zoe', 'Sam'], 'MATH200': ['Amir']}
Or the reverse: a list of dictionaries, one dictionary per
record — the natural shape for a batch of records where each one has
several named fields, replacing Chapter 7's
[order_id, amount, status] lists with named keys:
records = [
{"name": "Priya", "score": 91},
{"name": "Amir", "score": 84},
]
for record in records:
print(record["name"], record["score"])
# Priya 91
# Amir 84
["Priya", 91] only makes sense if you remember position 0
is a name. {"name": "Priya", "score": 91} says the same
thing self-documenting — record["score"] reads clearly
no matter how many fields a record has, which is exactly why real
APIs and databases hand back data shaped like this.
Go Deeper: nesting isn't limited to one level
Just like Chapter 7's nested lists, dictionaries can nest as deep
as the data actually needs —
company["engineering"]["Priya"]["projects"] is
perfectly valid Python. In practice, two levels (a record, and its
named fields) cover most real cases; going deeper is usually a
sign the data would be clearer split into several smaller
dictionaries instead.
- A nested dictionary is a dictionary whose values are themselves dictionaries — no special syntax needed.
data[outer_key][inner_key]reaches a single value: the first key picks the record, the second picks a field inside it.- A dict of lists groups values under names; a list of dicts represents a batch of named-field records — both combine directly with Chapter 7's list skills.
6. Real-world dictionaries & sets in production
- Tallying means counting occurrences into a dictionary, one pass through the data.
- Deduplicating means dropping repeats with a set, in one line.
- A dictionary as a lookup table replaces long chains of
if/elif.
.get() or in to build a dictionary or set as you go.
Word-frequency counting is one of the most common real dictionary
patterns — split some text into words, then tally each one using
.get()'s default to handle first-time-seen words safely:
text = "the cat sat on the mat the cat ran"
words = text.split() # Chapter 6's .split() -> a list of words
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
# {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'ran': 1}
That same counts.get(word, 0) + 1 line is worth pausing
on: the first time a word appears, .get() returns
0, so 0 + 1 stores 1. Every
time after that, it returns the running count so far, and adds one
more. Survey tallying uses the exact same shape:
responses = ["yes", "no", "yes", "yes", "maybe", "no"]
tally = {}
for r in responses:
tally[r] = tally.get(r, 0) + 1
for answer, count in tally.items():
print(f"{answer}: {count}")
# yes: 3
# no: 2
# maybe: 1
Sets solve a different, equally common problem: a list of raw form
submissions almost always has repeats, and set(...)
strips them out in a single line:
raw_emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
unique_emails = set(raw_emails)
print(len(raw_emails)) # 5 — with repeats
print(len(unique_emails)) # 3 — repeats dropped
Finally, a dictionary makes a clean lookup table —
a config or a set of fixed prices that would otherwise need a long
chain of if/elif statements:
shipping_rates = {"standard": 4.99, "express": 12.99, "overnight": 24.99}
method = "express"
print(f"Shipping cost: ${shipping_rates.get(method, 0):.2f}")
# Shipping cost: $12.99
if method == "standard": ... elif
method == "express": ..., and adding a new entry is a
one-line change instead of another elif.
Go Deeper: why not just use if/elif instead of .get()'s default?
You could write if word in counts: counts[word] += 1
else: counts[word] = 1 — it does the same thing as
counts[word] = counts.get(word, 0) + 1, just in four
lines instead of one. Both are correct; the .get()
version is simply the idiom experienced Python developers reach
for once counting-with-a-default becomes a familiar shape.
- Tallying counts occurrences with
counts[key] = counts.get(key, 0) + 1in one pass through the data. set(some_list)deduplicates a list's values in a single line.- A dictionary used as a lookup table replaces long
if/elifchains with one clean.get()call.
- Every JSON API response — user profiles, product catalogs, weather data — arrives in Python as nested dictionaries and lists, the exact shape Section 5 covers.
- Word counts, tag clouds, analytics dashboards, and "top N" reports all start from the same tally-with-a-dictionary pattern this chapter's capstone walked through.
- Sets back real production features directly — deduplicating a mailing list, checking "has this user ID already been processed today," and comparing two datasets for what changed are all one-line set operations instead of nested loops.
Points to Remember
- Dictionaries are written with
{key: value, ...}and looked up by key; a missing key raisesKeyError, while.get(key, default)avoids the crash. .update()merges in several keys;.pop()/delremove entries;.setdefault()inserts only if missing;.keys()/.values()/.items()expose a dictionary's parts.for key, value in some_dict.items():is the standard loop shape; dictionaries always preserve insertion order.- Sets hold unique values with no positions —
.add()/.remove()change them, and|/&/-compute union, intersection, and difference. - Nested dictionaries (
data[outer][inner]) model real records with named fields, and combine naturally with Chapter 7's lists as a dict of lists or a list of dicts. - Real-world code leans on
counts.get(key, 0) + 1for tallying,set(some_list)for deduplication, and dictionaries as lookup tables in place of longif/elifchains.