🐍 Python for Everyone

← Back to all chapters

Chapter 8 of 27 Beginner 30 min read

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

A user profile, a product catalog, a config file, a list of email addresses with no duplicates allowed — every one of these is naturally a dictionary or a set, not a list. Dictionaries store values under meaningful names instead of numbered positions; sets guarantee every value shows up exactly once. Together they're two of the most-used data structures in real Python code.
Sub-topic 1 of 6

1. Creating dictionaries & accessing values

At a glance
  • Dictionary = a collection of key: value pairs, 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.
Think in labels: a dictionary is a row of labeled boxes, not numbered ones — you ask for the box named "age", not the box at position 1.
What is... a dictionary? A dictionary is an unordered-by-lookup collection of 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.
creating_dicts.py
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:

Key → value structure of student
student = {"name": "Priya", "age": 22, "major": "CS"}

key       ->  value
"name"    ->  "Priya"
"age"     ->  22
"major"   ->  "CS"
accessing_by_key.py
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:

the_keyerror_crash.py
student = {"name": "Priya", "age": 22, "major": "CS"}
print(student["gpa"])
# KeyError: 'gpa'
What is... a KeyError? A 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:

using_get.py
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:

checking_with_in.py
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")
try_dicts.py
Click "Run Code" — try adding your own key, then look it up with .get().
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.

Quick recap
  • 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_dict checks for a key's existence before you risk accessing it.
Sub-topic 2 of 6

2. Dictionary methods that add, update, and remove

At a glance
  • .update() adds or overwrites several keys at once.
  • .pop(), .setdefault(), and del remove or safely insert entries.
  • .keys(), .values(), .items() hand back views of a dictionary's parts.
Use this when: an inventory, a config, or a user profile needs to grow, shrink, or get patched with new data.

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:

updating_a_dict.py
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}
What is... .update()? .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:

removing_and_defaulting.py
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:

keys_values_items.py
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)]
What is... .items()? .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.
try_dict_methods.py
Click "Run Code" — try setdefault on a brand-new key instead of an existing one.
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.

Quick recap
  • some_dict[key] = value adds 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.
Sub-topic 3 of 6

3. Looping over dictionaries

At a glance
  • 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.
Default habit: reach for .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:

looping_keys.py
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:

looping_items.py
scores = {"Priya": 91, "Amir": 84, "Zoe": 77}

for name, score in scores.items():
    print(name, "-", score)
# Priya - 91
# Amir - 84
# Zoe - 77
What is... insertion order? Insertion order means a dictionary always loops in the same order its keys were first added — not alphabetical, not random. Older versions of Python didn't guarantee this, but every Python you'll use today does, so a loop over 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:

accumulating_over_a_dict.py
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)
try_looping.py
Click "Run Code" — try adding a drink and looping again.
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.

Quick recap
  • for key in some_dict: loops over keys only; index back in with some_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.
Sub-topic 4 of 6

4. Sets: unique collections & set operations

At a glance
  • Set = an unordered collection with no duplicate values, ever.
  • .add() and .remove() change a set; in checks membership.
  • |, &, and - combine two sets: union, intersection, difference.
Use this when: you need "every unique value" — tags on a post, emails that already unsubscribed, IDs seen so far.
What is... a set? A set is a collection of unique values, written between curly braces like a dictionary but without the : 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.
creating_sets.py
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:

add_remove.py
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:

team_a vs. team_b, side by side
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
set_operations.py
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
What is... "unordered"? Unordered means a set doesn't track any particular position or insertion order for its values — printing the same set twice can even show the values in a different order each time. That's a trade-off for the speed of membership checks and duplicate removal; if order matters, keep using a list or a dictionary instead.
try_sets.py
Click "Run Code" — try a difference (-) between the two sets.
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.

Quick recap
  • A set holds unique values with curly braces and no : value part; duplicates are silently dropped.
  • .add() and .remove() change a set; value in some_set checks membership.
  • | (union), & (intersection), and - (difference) combine two sets in three different ways.
Sub-topic 5 of 6

5. Nested dictionaries & real-world records

At a glance
  • 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.
Use this when: each record has several named fields, and you have many records to keep track of by some ID or name.
What is... a nested dictionary? A nested dictionary is a dictionary where a value is itself another dictionary — no new syntax required, since a dictionary's values can be any type, including another dictionary. This is how Python represents "a record with named fields, for each of many entries."
nested_dicts.py
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:

updating_nested_dicts.py
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:

dict_of_lists.py
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:

list_of_dicts.py
records = [
    {"name": "Priya", "score": 91},
    {"name": "Amir", "score": 84},
]

for record in records:
    print(record["name"], record["score"])
# Priya 91
# Amir 84
What is... a list of dicts, compared to Chapter 7's nested lists? ["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.
try_nested_dicts.py
Click "Run Code" — try adding a new field to one of the inner dictionaries.
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.

Quick recap
  • 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.
Sub-topic 6 of 6

6. Real-world dictionaries & sets in production

At a glance
  • 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.
Pattern to remember: loop the data once, use .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:

word_frequency.py
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:

survey_tally.py
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:

deduplicating_emails.py
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:

lookup_table.py
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
What is... a lookup table? A lookup table is a dictionary used purely to map an input to a fixed result — a shipping method to its cost, a status code to its message, a country to its currency. It reads far more clearly than an equivalent chain of if method == "standard": ... elif method == "express": ..., and adding a new entry is a one-line change instead of another elif.
try_word_frequency.py
Click "Run Code" — try counting a sentence of your own.
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.

Quick recap
  • Tallying counts occurrences with counts[key] = counts.get(key, 0) + 1 in 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/elif chains with one clean .get() call.
In the Real World

Points to Remember

← All Chapters Take the Quiz →