Day 20 · ~14m

Dictionaries

Key-value pairs — creating dicts, accessing data, .get(), and avoiding KeyError.

🧑‍💻

Lists are great, but here's my problem. I have customer records — name, email, total purchases. With a list I'd need to remember "position 0 is the name, position 1 is the email..." That's going to get messy fast.

👩‍🏫

You've just discovered exactly why dictionaries exist. A dictionary stores key-value pairs — you look up a value by its key, not by position. Think of it like VLOOKUP in your spreadsheet, but instant:

customer = {"name": "Alice", "email": "alice@example.com", "total": 2450}
print(customer["name"])    # "Alice"
print(customer["total"])   # 2450

Keys are on the left of the colon, values on the right. You access values using square brackets with the key. No more remembering that position 0 means name. The code reads like English: customer["email"] — get the customer's email.

🧑‍💻

This is way better than having customer_name, customer_email, customer_total as separate variables. What happens if I look up a key that doesn't exist?

👩‍🏫

Python raises a KeyError — one of the most common errors you'll encounter:

customer = {"name": "Alice", "total": 2450}
print(customer["phone"])  # KeyError: 'phone'

This crashes your program. In the real world, data is messy — not every customer record has every field. That's where .get() comes in. It returns None (or a default you specify) instead of crashing:

customer.get("phone")            # None — no error
customer.get("phone", "N/A")     # "N/A" — custom default
customer.get("name")             # "Alice" — works normally for existing keys

Use bracket access [] when you're certain the key exists. Use .get() when it might not. It's the difference between assuming your data is clean and being smart about the fact that it never is.

🧑‍💻

How do I add new fields or update existing ones? Like, a customer changes their email.

👩‍🏫

Just assign to the key. If it exists, the value updates. If it doesn't, it's created:

customer = {"name": "Alice", "total": 2450}

# Update existing key
customer["total"] = 2750
print(customer)  # {"name": "Alice", "total": 2750}

# Add new key
customer["email"] = "alice@new.com"
print(customer)  # {"name": "Alice", "total": 2750, "email": "alice@new.com"}

Same syntax for both operations. Python doesn't distinguish between updating and creating — it just makes it work. Like editing a cell in your spreadsheet: if the cell has a value, you're updating it. If it's empty, you're filling it in. Either way, you just type.

🧑‍💻

Can I check if a key exists before accessing it?

👩‍🏫

Yes, with the in operator:

"name" in customer     # True
"phone" in customer    # False

if "email" in customer:
    print(customer["email"])
else:
    print("No email on file")

The in operator checks keys, not values. 2750 in customer would be False because 2750 is a value, not a key.

🧑‍💻

Can I delete a key? Like, removing a field that's no longer needed?

👩‍🏫

Two ways:

customer = {"name": "Alice", "total": 2750, "email": "alice@new.com"}

# del removes the key entirely
del customer["email"]
print(customer)  # {"name": "Alice", "total": 2750}

# .pop() removes and returns the value
total = customer.pop("total")
print(total)     # 2750
print(customer)  # {"name": "Alice"}

# .pop() with default — safe if key might not exist
customer.pop("phone", None)  # Returns None, no error

Just like list.pop(), dict.pop() gives you the removed value. And like .get(), you can provide a default to avoid errors on missing keys.

🧑‍💻

What types can be keys? Can I use anything?

👩‍🏫

Keys must be immutable — strings, numbers, booleans, and tuples work. Lists and other dictionaries cannot be keys:

# These work
data = {"name": "Alice", 42: "answer", True: "yes"}

# This does NOT work
# data = {[1, 2]: "nope"}  # TypeError: unhashable type: 'list'

In practice, 99% of the time your keys will be strings. Values can be anything — strings, numbers, lists, even other dictionaries. A dictionary of customer records where each value is itself a dictionary? That's how real applications model data.

Let's build some dictionaries.

Practice your skills

Sign up to write and run code in this lesson.

Already have an account? Sign in