Python
Topic 9 · Python basics

Dictionaries & Sets: Look Things Up Fast

Store values by name instead of by position: create dictionaries, read, add, update and delete entries, loop over keys and values, count things, use nested records like JSON, and remove duplicates and compare groups with sets.

Show:
In this topic
Beginner

Dictionaries: values by name

A list finds things by position: item 0, item 1. Often you want to find things by name instead: a phone number by person, a price by product, a patient's record by ID. A dictionary (dict) stores key → value pairs, like a real dictionary stores word → meaning.

prices = {"coffee": 4.5, "tea": 3.0, "muffin": 5.25} # key value

Keys are usually strings or numbers, and each key appears only once. Values can be anything, including lists and other dictionaries.

Python
prices = {"coffee": 4.5, "tea": 3.0, "muffin": 5.25}
print(prices["tea"])            # look up by key: 3.0
prices["juice"] = 6.0           # add a new pair
prices["coffee"] = 4.8          # update an existing one
del prices["muffin"]            # delete a pair
print(prices)
print(len(prices), "coffee" in prices, "cake" in prices)
Open in playground ↗
Beginner

Safe look-ups with get

Looking up a key that is not there, prices["cake"], stops the program with a KeyError. Two ways to avoid it: check first with in, or use .get(key, default), which returns the default (or None) instead of crashing.

Python
stock = {"apples": 12, "pears": 0}
print(stock.get("apples"))        # 12
print(stock.get("kiwis"))         # None, no crash
print(stock.get("kiwis", 0))      # 0: our chosen default

item = "kiwis"
if item in stock:
    print(stock[item])
else:
    print(item, "not stocked")
Open in playground ↗
Beginner

Looping over a dictionary

A for loop over a dictionary gives its keys. Use .values() for the values, and .items() for (key, value) pairs, which is what you want most of the time.

Python
ages = {"Sita": 27, "Leo": 31, "Mia": 24}
for name in ages:
    print(name)
for age in ages.values():
    print(age)
for name, age in ages.items():
    print(f"{name} is {age}")

print(list(ages.keys()), sum(ages.values()))
oldest = max(ages, key=ages.get)      # the key with the largest value
print("oldest:", oldest)
Open in playground ↗
Beginner

Counting with a dictionary

The classic dictionary job: count how often each thing appears. For each item, take the current count (0 if new) and add 1. The same pattern counts words in text, orders per customer or diagnoses per clinic.

Python
votes = ["tea", "coffee", "tea", "juice", "coffee", "tea"]
counts = {}
for v in votes:
    counts[v] = counts.get(v, 0) + 1
print(counts)            # {'tea': 3, 'coffee': 2, 'juice': 1}

# the most popular, by sorting the (key, value) pairs by value
ranking = sorted(counts.items(), key=lambda pair: pair[1], reverse=True)
print(ranking[0])

# the standard library has a ready-made counter
from collections import Counter
print(Counter(votes).most_common(2))
Open in playground ↗
Try it

Watch a dictionary being built

Step through the counting loop and watch the dictionary grow.

Interactive: this part runs in your browser.

Beginner

Grouping with a dictionary of lists

Another everyday pattern: collect items into groups. Each key holds a list, and you append to the right list.

Python
orders = [("Sita", 30), ("Leo", 12), ("Sita", 18), ("Mia", 40), ("Leo", 7)]
by_customer = {}
for name, amount in orders:
    if name not in by_customer:
        by_customer[name] = []        # first order for this person: start a list
    by_customer[name].append(amount)
print(by_customer)

for name, amounts in by_customer.items():
    print(f"{name}: {len(amounts)} orders, total {sum(amounts)}")
Open in playground ↗
Beginner

Nested data: records like JSON

Real data often arrives as a list of dictionaries, one dictionary per record. This is exactly the shape of JSON from a web API, and pandas turns it straight into a table. To reach inside, index step by step: first the list position, then the key, then perhaps a list again.

Python
patients = [
    {"id": 1, "name": "Sita", "age": 27, "visits": ["2026-01-10", "2026-03-02"]},
    {"id": 2, "name": "Leo",  "age": 64, "visits": []},
    {"id": 3, "name": "Mia",  "age": 41, "visits": ["2026-02-14"]},
]
for p in patients:
    print(p["name"], "has", len(p["visits"]), "visits")

print(patients[0]["visits"][-1])        # Sita's last visit
older = [p["name"] for p in patients if p["age"] >= 40]
print(older)
Open in playground ↗
Beginner

Sets: unique items

A set is an unordered collection with no duplicates, written with curly brackets: {"a", "b"} (an empty set is set(), because {} is an empty dictionary). Sets are perfect for two jobs:

  • Removing duplicates: set(items).
  • Comparing groups: which items are in both, in either, or only in one.

Checking x in my_set is instant however big the set is, while x in my_list has to look at every item. With millions of items that difference is huge.

Python
emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
unique = set(emails)
print(unique, len(unique))

python_class = {"Sita", "Leo", "Mia", "Ana"}
sql_class = {"Leo", "Ana", "Zoe"}
print(python_class & sql_class)     # in both: intersection
print(python_class | sql_class)     # in either: union
print(python_class - sql_class)     # only in python_class: difference

seen = set()
seen.add("Sita")
print("Sita" in seen, "Leo" in seen)
Open in playground ↗
Beginner

Which collection should I use?

You needUseExample
an ordered sequence you will changelist [ ]scores over time, a to-do list
a small fixed group of valuestuple ( )(latitude, longitude)
to look things up by a name or IDdict {key: value}product → price, id → record
unique items, fast "is it in there?"set { }emails already seen
Beginner

Practice: check yourself

Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.

Exercise 1. Price list

prices = {"tea": 3.0, "coffee": 4.5}. Add "cake" at 5.0, change coffee to 4.8, then set order_total to the cost of 2 coffees and 1 cake (14.6).

Exercise 2. Word counts

Build counts, a dictionary of how many times each word appears in text = "red blue red green blue red", using a loop (not Counter). Then set most to the most common word.

Exercise 3. Common friends

Using sets, set both to the friends Sita and Leo share, and only_sita to Sita's friends who are not Leo's.

Beginner

Summary

Dictionaries map keys to values: look up with d[key] or safely with d.get(key, default), loop with .items(), and use them to count and group. Sets hold unique items and compare groups with & | -.

Key words

dictionary
a collection of key → value pairs: {"tea": 3.0}
key
the name you look a value up by; unique in a dictionary
value
what a key refers to
KeyError
the error from looking up a key that is not there
set
an unordered collection with no duplicates
JSON
a text format for data that looks like Python lists and dictionaries

Common mistakes

  • KeyError from d["missing"]: use in or .get().
  • {} makes an empty dictionary, not a set. Use set().
  • Expecting a set to keep order or support indexing: my_set[0] is an error.
  • Looping with for k, v in d: (a ValueError). You need d.items().
  • Using a list as a key: keys must be unchangeable (strings, numbers, tuples).
Check yourself

Quiz

1. d = {"a": 1, "b": 2}. What is d["b"]?

2. What does d.get("z", 0) return if "z" is not a key?

3. Which loop gives you both keys and values?

4. What is len(set([1, 1, 2, 3, 3, 3]))?

5. You need to check, millions of times, whether an ID has been seen before. Which collection?

6. What does {"a", "b"} & {"b", "c"} give?

Ready