Dictionaries

Look things up by name, not position

Beginner 11 min

In this lesson

A dictionary stores pairs: a key and the value it points to. Instead of looking things up by position like a list, you look them up by a meaningful name. It’s perfect for ‘this goes with that’ data.

Explain it like I’m 5

A dictionary is like a real dictionary: you look up a word (the key) and get its meaning (the value). You don’t care what page it’s on — you find it by the word itself.

Keys and values

Write a dictionary with curly braces and key: value pairs: ages = {"Ada": 36, "Linus": 54}. You read a value by its key: ages["Ada"] gives 36. Keys are usually strings or numbers and must be unique; values can be anything. There’s no index — the key is how you find things.

Example
ages = {"Ada": 36, "Linus": 54}
print(ages["Ada"])
print(ages["Linus"])
Output
36
54
Look a value up by its key, not a position.

Adding, updating, and removing

Assigning to a new key adds it: ages["Grace"] = 41. Assigning to an existing key updates it: ages["Ada"] = 37. del ages["Linus"] removes a pair. Because each key is unique, writing to a key either creates or overwrites — there are never duplicates.

Example
stock = {"apples": 12, "pears": 5}
stock["bananas"] = 8     # add a new key
stock["apples"] = 9      # update an existing key
del stock["pears"]       # remove a key
print(stock)
Output
{'apples': 9, 'bananas': 8}
Add, update, and delete pairs.

Safe access with .get()

Asking for a missing key with ages["Bob"] raises a KeyError and stops your program. ages.get("Bob") returns None instead, and ages.get("Bob", 0) returns a default of your choice. Use .get() whenever a key might be absent. The in operator also tests presence: "Ada" in ages.

Example
prices = {"coffee": 3, "tea": 2}
print(prices.get("coffee", 0))
print(prices.get("juice", 0))
Output
3
0
.get() avoids errors for missing keys.

Count how many times each letter appears in the word. Run it to see the tally for 'banana'.

word = "banana"
counts = {}
for letter in word:
    counts[letter] = counts.get(letter, 0) + 1
print(counts)

Looping over a dictionary

Looping over a dict gives its keys: for name in ages:. To get keys and values together, use .items(): for name, age in ages.items():. There’s also .keys() and .values(). When to use a dict vs a list: a list is for ordered items you reach by position; a dict is for looking things up by a name or id.

Example
scores = {"Ada": 90, "Bo": 75, "Cy": 88}

for name, score in scores.items():
    print(name, "scored", score)
Output
Ada scored 90
Bo scored 75
Cy scored 88
.items() gives each key and value together.

Nested dictionaries and setdefault()

A dictionary’s values can themselves be dictionaries, which is how you model structured records — each person with their own age, city, and so on under one key. You reach in with repeated keys: people["ada"]["city"].

.setdefault(key, default) reads a key but inserts a default first if it’s missing — a tidy way to build up groups without checking ‘does this key exist yet?’ every time. (Structured data like this is commonly saved as JSON, which the standard library’s json module handles — learn more about modules here.)

Example
people = {
    "ada": {"age": 36, "city": "London"},
    "bo": {"age": 41, "city": "Oslo"},
}
print(people["ada"]["city"])

groups = {}
groups.setdefault("python", []).append("ada")
groups.setdefault("python", []).append("bo")
print(groups)
Output
London
{'python': ['ada', 'bo']}
Reaching into nested dicts, and building lists with setdefault.

Common mistake: KeyError when a key doesn't exist

Why it happens:

Accessing d["missing"] raises a KeyError because there’s no such key.

How to fix it:

Check with if key in d: or use d.get(key, default) to supply a fallback value instead of crashing.

How do you read a value from a dictionary?

What does d.get("x", 0) do when "x" is missing?

Mini exercise (medium)

Given a list of words ["red", "blue", "red", "green", "blue", "red"], build a dictionary mapping each word to how many times it appears, then print it.

Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.

words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for word in words:
    # TODO: add 1 to this word’s count
    pass
print(counts)

What to learn next

You learned to store key-value pairs, create and read dictionaries, add and update entries, access them safely with .get(), and loop over keys and values. You used .get() to tally how many times each word appeared in a list.

There’s one more built-in collection, tuned for a specific job: tracking unique items. Sets covers removing duplicates, fast membership checks, and the union, intersection, and difference operations. When you’re ready, continue to the next lesson.