// python · beginner

Python Dictionaries Explained: Keys, Values and Real Examples

Learn how Python dictionaries store data as key-value pairs, how to add, update and look up values safely, loop over them, and count things with them.

Lists are great when order matters, but sometimes you want to look things up by name rather than by position. What’s Ava’s score? What’s the capital of Japan? How many times does each word appear? For jobs like these, Python has dictionaries.

What is a dictionary?

A dictionary stores key-value pairs. You give it a key, and it gives you back the matching value, just like looking up a word in a real dictionary to find its meaning.

python
ages = {"Ava": 15, "Leo": 17, "Mia": 16}
  • Curly braces {} make a dictionary.
  • Each pair is written key: value.
  • Pairs are separated by commas.

Keys are usually strings or numbers, and each key can only appear once. Values can be anything: numbers, strings, lists or even other dictionaries.

Looking up a value

Use the key in square brackets:

python
ages = {"Ava": 15, "Leo": 17, "Mia": 16}
print(ages["Leo"])   # 17

If the key doesn’t exist, you get a KeyError:

python
print(ages["Sam"])   # KeyError: 'Sam'

There are two safe ways to avoid that. Check first with in, or use .get(), which returns None (or a default you choose) instead of crashing:

python
if "Sam" in ages:
    print(ages["Sam"])

print(ages.get("Sam"))        # None
print(ages.get("Sam", 0))     # 0

Adding, changing and removing

python
ages = {"Ava": 15, "Leo": 17}

ages["Mia"] = 16     # add a new key
ages["Ava"] = 16     # change an existing value
del ages["Leo"]      # remove a key

print(ages)          # {'Ava': 16, 'Mia': 16}

Notice that adding and changing use exactly the same syntax. If the key exists, its value is replaced; if not, it’s created.

.pop() removes a key and gives you its value at the same time:

python
mia_age = ages.pop("Mia")
print(mia_age)   # 16

Looping over a dictionary

By default, looping over a dictionary gives you its keys:

python
capitals = {"France": "Paris", "Japan": "Tokyo", "Kenya": "Nairobi"}

for country in capitals:
    print(country)

Most of the time you want both the key and the value, so use .items():

python
for country, city in capitals.items():
    print(f"The capital of {country} is {city}.")

There’s also .keys() for just the keys and .values() for just the values:

python
print(list(capitals.values()))   # ['Paris', 'Tokyo', 'Nairobi']

Since Python 3.7, dictionaries remember the order you added items in.

Lists vs dictionaries

Use a list when… Use a dictionary when…
the order of items matters you look things up by a name or ID
items are all the same kind of thing each value has a label
you’d say “the first one, the second one…” you’d say “the one called…”
e.g. a queue of tasks e.g. a phone book, a settings menu

Storing records

A dictionary is a great way to describe one thing with several properties:

python
student = {
    "name": "Ava",
    "age": 15,
    "languages": ["Python", "HTML"],
}

print(student["name"])               # Ava
print(student["languages"][0])       # Python
student["languages"].append("SQL")

And a list of dictionaries is a simple way to store a whole table of data:

python
students = [
    {"name": "Ava", "score": 82},
    {"name": "Leo", "score": 67},
    {"name": "Mia", "score": 91},
]

for s in students:
    if s["score"] >= 70:
        print(f"{s['name']} passed")

Notice the single quotes inside the f-string: s['name']. Using double quotes there would end the f-string early in older versions of Python.

Counting things

Counting is one of the most common dictionary jobs. Here’s how to count how often each word appears in a sentence:

python
sentence = "the cat sat on the mat the end"
counts = {}

for word in sentence.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)
# {'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1}

counts.get(word, 0) returns the current count, or 0 the first time we see a word, then we add 1. This little pattern is worth memorising.

Mini project: a pocket glossary

python
glossary = {
    "variable": "a name that points to a value",
    "loop": "code that repeats",
    "function": "a named, reusable block of code",
}

while True:
    term = input("Look up a term (or 'quit'): ").strip().lower()
    if term == "quit":
        break
    if term in glossary:
        print(f"{term}: {glossary[term]}")
    else:
        meaning = input(f"I don't know '{term}'. What does it mean? ")
        glossary[term] = meaning
        print("Thanks, I've saved it!")

print(f"The glossary now has {len(glossary)} terms.")

It looks up terms, and when it meets a new one, it asks you to teach it. Challenge: at the end, print every term in alphabetical order using sorted(glossary). In the files guide you’ll learn how to save it so it remembers between runs.

Key points

  • Dictionaries store key: value pairs and look values up by key.
  • d[key] = value both adds and updates.
  • Use in or .get() to avoid a KeyError.
  • Loop with .items() to get keys and values together.
  • counts[x] = counts.get(x, 0) + 1 is the classic counting pattern.

Things will go wrong sometimes. Learn to handle errors gracefully in Python try and except.