Skip to content
Hands-on Mentor
ENTR
Back to blog

Python dictionary tutorial: store and look up data by key

A Python dictionary stores data as key-value pairs. Learn to create one, loop through it, check if a key exists, and count items with the Corner Café menu.

4 min read

A Python dictionary (dict) stores data as key-value pairs. You look up a value by its key, not by a position like in a list. Use a dictionary when you want to ask "what is the price of a latte?" and get an answer by name.

In this tutorial you will use the menu of Corner Café, a small café in the fictional port city Port Alder, owned by Ada.

How do you create a dictionary in Python?

Write curly braces with key: value pairs separated by commas.

menu = {"latte": 4.25, "tea": 1.25, "cookie": 2.00}
print(menu["latte"])
print(len(menu))

menu["latte"] returns the value for the key "latte". len(menu) counts the pairs. Each key can appear only once.

You can add a new pair or change an existing one with the same syntax:

menu = {"latte": 4.25, "tea": 1.25}
menu["lemonade"] = 3.25
menu["tea"] = 1.50
print(menu)

If the key does not exist, Python adds it. If it exists, Python replaces the value. A dictionary keeps pairs in the order you added them, so lemonade comes last.

How do you check if a key exists in a dictionary?

Use in. It returns True or False and only looks at keys.

menu = {"latte": 4.25, "tea": 1.25}
print("latte" in menu)
print(4.25 in menu)
print(4.25 in menu.values())

To read a key that might be missing, use get. Reading a missing key with square brackets stops your program with a KeyError.

menu = {"latte": 4.25, "tea": 1.25}
print(menu.get("water"))
print(menu.get("water", 0.75))

get returns None for a missing key, or the default value you pass as the second argument. Writing menu["water"] instead would stop the program with KeyError: 'water'.

How do you loop through a dictionary in Python?

Use items() to get each key and value together.

menu = {"latte": 4.25, "tea": 1.25, "cookie": 2.00}

for item, price in menu.items():
    print(f"{item}: ${price:.2f}")

These three methods cover most loops:

  • menu.keys() gives the keys.
  • menu.values() gives the values.
  • menu.items() gives (key, value) pairs.

A plain for item in menu: loops over the keys only.

What are the most useful Python dict methods?

Here are the ones you will use first.

MethodWhat it does
get(key, default)Reads a value, with a safe default
pop(key)Removes a key and returns its value
del menu[key]Removes a key
keys(), values(), items()Views for looping
update(other)Adds pairs from another dictionary
menu = {"latte": 4.25, "tea": 1.25, "cookie": 2.00}
del menu["cookie"]
price = menu.pop("tea")
print(menu, price)

How do you count items with a dictionary?

Counting is one of the best uses of a dictionary. Let's count how many of each drink Maya sold today:

orders = ["tea", "latte", "tea", "lemonade", "tea", "latte"]
counts = {}
for item in orders:
    counts[item] = counts.get(item, 0) + 1
print(counts)

The first time Python sees tea, counts.get("tea", 0) returns 0, and the code stores 1. Without get, the first tea would raise a KeyError.

When should you use a dictionary instead of a list?

SituationUse
An ordered sequence of items (orders)List
Values you find by name (item to price)Dictionary
The fields of one record (name, age, city)Dictionary
Many recordsList of dictionaries

The last row is the shape of real data. Each order is a dictionary, and all orders are a list:

menu = {"latte": 4.25, "tea": 1.25, "cookie": 2.00}
orders = [
    {"item": "tea", "quantity": 3},
    {"item": "latte", "quantity": 1},
]

total = 0
for order in orders:
    total += menu[order["item"]] * order["quantity"]
print(f"Total: ${total:.2f}")

The price comes from menu by item name. The quantity comes from the order's own dictionary.

What mistakes do beginners make with dictionaries?

  • Using a position as a key. menu[0] does not return the first item. It raises a KeyError.
  • Reading a key that is missing. Use get when you are not sure the key exists.
  • Using a list as a key. Keys must be unchangeable: strings, numbers, or tuples.
  • Mixing letter case. "Latte" and "latte" are two different keys. Pick one style.

What to read next

  • Build the Corner Café menu step by step in the lesson [Dictionaries: key and value](/learn/python/dictionary-key-value).
  • Practice looping and counting in [Looping and counting with dictionaries](/learn/python/dict-loops-counting).
  • Put your values in functions with [Python functions](/blog/python-functions).
  • See all lessons in the [Python course](/courses/python).
  • #python
  • #dictionary
  • #dict
  • #data structures
All posts