fuckingpython.lol

Learn Python › Lesson 9

Python dictionaries: look stuff up by name, not by damn position

Updated · every example run on Python 3.9 to 3.15

A list is great until you have to remember that the cat's weight lives at position 2. Was it 2? Or 3, after you added the age? A dictionary drops the numbers and lets you use labels: cat["weight_kg"] instead of cat[2]. You ask for the thing by name, and you get the thing.

Python calls it a dict, and it is everywhere. Settings, price lists, word counts, the JSON a web API sends back once Python has read it in: they all end up as dictionaries. Learn this one and half of the code you will ever read starts making sense.

Make a dictionary

Curly braces, and inside them key: value pairs separated by commas. To read a value, put its key in square brackets, the way you put an index after a list.

main.py
prices = {"milk": 1.99, "eggs": 3.49, "coffee": 12.0}
print(prices)
print(prices["coffee"])
print(len(prices))

cat = {"name": "Biscuit", "age": 4, "weight_kg": 5.2, "likes_humans": False}
print(cat["name"], "is", cat["age"], "and weighs", cat["weight_kg"], "kg")
Python 3.9 to 3.15 all print
{'milk': 1.99, 'eggs': 3.49, 'coffee': 12.0}
12.0
3
Biscuit is 4 and weighs 5.2 kg

len counts the pairs, not the keys and values separately, so three items give 3. The values can be anything and can mix types: a string, an int, a float and a bool all live happily in cat. When Python prints a whole dict it uses single quotes around strings; that is just its taste, your double quotes were fine. An empty dictionary is {}.

A key that isn't there: KeyError

A list complains when you ask for a position past its end. A dict complains when you ask for a key it has never heard of:

main.py
stock = {"apples": 12, "bananas": 0, "pears": 5}
print(stock["bananas"])
print(stock["mangoes"])
Python 3.15 prints
0
Traceback (most recent call last):
  File "/home/me/project/main.py", line 3, in <module>
    print(stock["mangoes"])
          ~~~~~^^^^^^^^^^^
KeyError: 'mangoes'
PythonPrints
3.9–3.15KeyError: 'mangoes'

Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.

bananas works even though it is 0: the key exists, it just holds a sad number. mangoes doesn't exist, so Python stops with KeyError, and the message is nothing but the missing key in quotes. That makes it the easiest error in Python to read and one of the most fucking annoying to get, because the usual cause is a typo or a capital letter: "Apples" and "apples" are two different keys. The KeyError page lists where missing keys tend to come from.

get and in: check before it blows up

When a key might be missing and that's fine, use get. It returns None for a missing key instead of raising, or a default you choose. To ask whether a key is there at all, use in.

main.py
stock = {"apples": 12, "bananas": 0, "pears": 5}

print(stock.get("mangoes"))
print(stock.get("mangoes", 0))
print(stock.get("apples", 0))

print("pears" in stock)
print("mangoes" in stock)
print(12 in stock)

if "bananas" in stock:
    print("Bananas in stock:", stock["bananas"])
Python 3.9 to 3.15 all print
None
0
12
True
False
False
Bananas in stock: 0

Look at 12 in stock: it is False, although 12 is right there. in checks the keys, never the values. If you really want to search the values, ask for them: 12 in stock.values() is True.

Add, change and delete

Assign to a key to add it. Assign to a key that already exists and you replace its value, with no warning whatsoever: a dict holds exactly one value per key.

main.py
cart = {"milk": 1}
cart["eggs"] = 12
cart["milk"] = 2
cart.update({"bread": 1, "eggs": 6})
print(cart)

del cart["bread"]
print(cart)

removed = cart.pop("eggs")
print("Put back", removed, "eggs")
print(cart)

print(cart.pop("caviar", "never had any"))
Python 3.9 to 3.15 all print
{'milk': 2, 'eggs': 6, 'bread': 1}
{'milk': 2, 'eggs': 6}
Put back 6 eggs
{'milk': 2}
never had any

update pours another dict into this one, adding new keys and overwriting the ones that match, which is how the eggs went from 12 to 6. Notice the eggs kept their place in line: replacing a value doesn't move the key. del removes a key and raises KeyError if it isn't there. pop removes a key and hands you its value, and with a second argument it returns that instead of raising when the key is missing. Nobody ever had caviar.

Loop over a dictionary and count things

The single most useful thing a dictionary does for a beginner is count shit. Loop over a list, use each item as a key, and add one every time you see it:

main.py
votes = ["pizza", "tacos", "pizza", "sushi", "pizza", "tacos"]

counts = {}
for food in votes:
    counts[food] = counts.get(food, 0) + 1
print(counts)

for food in counts:
    print(food)

for food, n in counts.items():
    print(f"{food}: {n}")

print(sum(counts.values()), "votes in total")
Python 3.9 to 3.15 all print
{'pizza': 3, 'tacos': 2, 'sushi': 1}
pizza
tacos
sushi
pizza: 3
tacos: 2
sushi: 1
6 votes in total

counts.get(food, 0) + 1 reads "what I had so far, or zero the first time, plus one". No if, no KeyError.

A plain for over a dict gives you the keys. .items() gives you key and value together, and you unpack them into two names exactly like for i, item in enumerate(...) in the loops lesson. .values() gives just the values, and sum adds them up. The order is the order the keys were first added, and since Python 3.7 that is a promise of the language, not luck.

Forget the .items() and write for food, n in counts:, and you are back in the loops lesson's two-names trap: Python tries to split each key, the string "pizza", into two variables. Five letters into two names: ValueError: too many values to unpack.

Keys must be hashable

To find a key fast, a dict turns it into a number called a hash, and that number must never change while the key is stored. So the usual keys are things that can't change: strings, numbers, bools, None, and tuples of those. A tuple is like a list written in parentheses instead of square brackets, except that it can never be modified, which makes it perfect for keys made of two parts, like a seat in a movie theater.

main.py
seats = {}
seats[("row 3", 12)] = "Ada"
seats[("row 3", 13)] = "Grace"
print(seats[("row 3", 12)])
print(len(seats))

seats[["row 4", 1]] = "Sam"
Python 3.15 prints
Ada
2
Traceback (most recent call last):
  File "/home/me/project/main.py", line 7, in <module>
    seats[["row 4", 1]] = "Sam"
    ~~~~~^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
PythonPrints
3.9–3.13TypeError: unhashable type: 'list'
3.14–3.15TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.

The tuples work. The list, in square brackets, can change, so it has no hash and Python refuses it. Up to Python 3.13 the error is TypeError: unhashable type: 'list'. Python 3.14 and 3.15 explain themselves better, "cannot use 'list' as a dict key", and keep the old wording in parentheses at the end. The fix is to make the key a tuple. Values have no such rule: a value can be a list, another dict, whatever the hell you want.

Try it yourself

Write a function total(cart, prices) that returns what a cart costs. Each key in cart is a product and its value is how many you take. A product that isn't in prices costs nothing. With the data below it should print 5.25.

cart = {"milk": 2, "bread": 1, "unicorn": 1}
prices = {"milk": 1.5, "bread": 2.25, "eggs": 3.0}
Show the answer
def total(cart, prices):
    result = 0
    for product, quantity in cart.items():
        result = result + prices.get(product, 0) * quantity
    return result

cart = {"milk": 2, "bread": 1, "unicorn": 1}
prices = {"milk": 1.5, "bread": 2.25, "eggs": 3.0}
print(total(cart, prices))

prices.get(product, 0) is what keeps the unicorn from crashing everything with a KeyError.

Questions

How do I check if a key exists in a Python dictionary?

Use in: "milk" in prices is True or False. It checks keys only; for values, use value in prices.values().

What is the difference between get() and square brackets?

prices["milk"] raises KeyError when the key is missing. prices.get("milk") returns None instead, and prices.get("milk", 0) returns the default you give it.

Are Python dictionaries ordered?

Yes. Since Python 3.7 a dict keeps its keys in the order they were first inserted, and loops and print follow that order. Changing a value doesn't move its key; deleting it and adding it again puts it at the end.

Can a dictionary have duplicate keys?

No. A key appears once, and assigning to it again replaces the value. If you type the same key twice in braces, as in {"a": 1, "a": 2}, the last one wins and you get {'a': 2}.

Sources

Read on November 11, 2026.