Skip to content

Dictionaries

By the end of this lesson you'll be able to:

  • Create a dictionary and access values by key
  • Safely retrieve values with get() to avoid KeyError
  • Add, update, and remove entries, and iterate over keys, values, and items
  • Use nested dictionaries and dictionary comprehensions

A dictionary maps keys to values — exactly like a real-world dictionary maps words to definitions. Dictionaries are one of the most widely-used data structures in Python.

Welcome to Chapter 21!

Monty waving welcome Imagine a phone book that you can look up in any order, add new contacts to, and search in an instant. That's a Python dictionary! Let's build one. Let's code it together!

Creating a Dictionary

A dictionary is created with curly braces {}. Each entry is a key: value pair, separated by commas.

1
2
3
4
5
phone_book = {
    "Alice": "555-1234",
    "Bob":   "555-5678",
    "Carol": "555-9012"
}

Keys must be unique within a dictionary. Keys are usually strings or numbers. Values can be anything — strings, numbers, lists, even other dictionaries.


  

Accessing Values by Key

Use square brackets with the key to retrieve a value:

1
phone_book["Alice"]   # "555-1234"

If the key doesn't exist, Python raises a KeyError — so be careful.

What Do You Think Will Happen?

Monty thinking The code below tries to access both a key that exists and one that doesn't. What do you think happens when a key is missing? Make your guess — then run it!


  

Safe Access with get()

dict.get(key) returns the value if the key exists, or None if it doesn't — no crash. You can also provide a default value: dict.get(key, default).

1
2
3
4
grades = {"Alice": 95, "Bob": 87}
print(grades.get("Alice"))          # 95
print(grades.get("Dave"))           # None
print(grades.get("Dave", 0))        # 0 — custom default

Use get() whenever you're not sure whether a key exists.

See It: A Cabinet of Labeled Drawers

A dictionary works like a cabinet where every drawer has its key written on the front — Python jumps straight to the right drawer without opening the others. Before you try the lookup below, predict: what happens if you type Grace with a capital G instead of grace?

Explore the Dictionary Key Lookup MicroSim

Try a missing key both ways: with square brackets you get the KeyError crash, and with the .get() checkbox you get a polite None. Then check compare with a list search — the list has to check drawer after drawer, while the dictionary always takes one hop. That difference is why phone books, glossaries, and game inventories all use dictionaries.

Adding and Updating Entries

Add a new key or update an existing one using the same assignment syntax:

1
2
grades["Dave"] = 78     # new key
grades["Alice"] = 96    # update existing key

  

Removing Entries

  • d.pop(key) — removes the key and returns its value (raises KeyError if missing unless you pass a default)
  • del d[key] — removes the key (raises KeyError if missing)
1
2
grades.pop("Bob")      # removes Bob, returns 87
del grades["Carol"]    # removes Carol

Keys, Values, and Items

Three dictionary methods give you different views of the data:

  • d.keys() — all keys
  • d.values() — all values
  • d.items() — all (key, value) pairs as tuples

  

Iterating over a Dictionary

You can loop over keys, values, or key-value pairs:

1
2
3
4
5
6
7
# Loop over keys:
for name in scores:
    print(name)

# Loop over key-value pairs (most common):
for name, score in scores.items():
    print(f"{name}: {score}")

Key Membership with in

Use in to check whether a key exists without causing a KeyError:

1
2
if "Alice" in scores:
    print("Alice's score:", scores["Alice"])

Nested Dictionaries

A dictionary can contain other dictionaries as values. This is perfect for representing structured data — like a contacts list where each contact has several fields.

1
2
3
4
5
6
7
contacts = {
    "Alice": {"phone": "555-1234", "email": "alice@example.com"},
    "Bob":   {"phone": "555-5678", "email": "bob@example.com"}
}

# Access Alice's phone:
print(contacts["Alice"]["phone"])

Dictionary Comprehensions

A dictionary comprehension builds a new dictionary from an existing sequence, similar to a list comprehension.

Syntax: {key_expr: value_expr for item in iterable}

Before the comprehension, here's the long-form equivalent to make the pattern clear:

1
2
3
4
5
6
7
# Long way:
squares = {}
for n in range(1, 6):
    squares[n] = n * n

# Comprehension — same result:
squares = {n: n * n for n in range(1, 6)}

The Default Dictionary Pattern

A common pattern is building a dictionary where missing keys should start with a default value. The manual approach uses get():

1
2
3
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1

  

Learning Check

Your Turn — Build a Grade Book

Monty thinking The code below creates an empty grade book. Add three students — "Alice" with 95, "Bob" with 87, and "Carol" with 91 — then print each student's name and grade using a for loop over .items().


  

Experiments

Try these changes. Predict what will happen first, then run it to check!

  1. Create a dictionary of capital cities: {"France": "Paris", "Japan": "Tokyo", "Brazil": "Brasília"}. Print the capital of Japan. You'll know it worked when you see Tokyo.

  2. Add a new country to your capitals dictionary and print all keys. You'll know it worked when the new country appears in the key list.

  3. Use a dictionary comprehension to create {1: 1, 2: 8, 3: 27, 4: 64, 5: 125} (cubes of 1–5). You'll know it worked when you see those five key-value pairs.

  4. Try capitals.get("Germany", "Unknown") when "Germany" isn't in the dictionary. You'll know it worked when you see "Unknown" instead of a KeyError.

  5. Count the frequency of each letter in "mississippi" using the default dictionary pattern. You'll know it worked when you see {"m": 1, "i": 4, "s": 4, "p": 2}.

Dictionary Wizard!

Monty celebrating You've mastered one of Python's most powerful data structures! Dictionaries are everywhere — in APIs, configuration files, databases, and machine learning models. Next chapter we'll combine all four collection types with Python's powerful built-in functions!

Take the Chapter Review Quiz

See Annotated References