📒
Coding🎓 Ages 14-18Intermediate 12 min read

Dictionaries in Python

Learn dictionaries in Python: store data as key-value pairs, look up and update values, loop over items, and avoid KeyErrors with get. Runnable code, a worked example and a quiz for teens.

Key takeaways

  • A dictionary stores data as key-value pairs inside curly braces { }
  • You look up a value by its key, not by a numbered position
  • Assigning to a new key adds it; assigning to an existing key updates it
  • .get() safely returns a default instead of crashing on a missing key
  • Looping with .items() gives you each key and value together

Storing labelled data

A list is great when you have an ordered row of items and you reach them by position: scores[0], scores[1], and so on. But often a position number isn't meaningful. If you're storing test scores, you'd rather look them up by subject — scores["maths"] — than by remembering that maths happens to be item 3.

That's exactly what a dictionary gives you. A dictionary stores data as key-value pairs: each piece of data (the value) is labelled with a unique name (the key). It works just like a real dictionary, where you look up a word (the key) to find its definition (the value).

Creating a dictionary

You write a dictionary with curly braces, putting key: value pairs inside, separated by commas:

student = {
    "name": "Aisha",
    "age": 15,
    "grade": "A"
}

print(student)

Line by line:

  • The braces { } mark the dictionary.
  • Each pair has a key on the left of the colon and a value on the right. Here the keys are strings ("name", "age", "grade").
  • Pairs are separated by commas. Spreading them over several lines is just for readability.

An empty dictionary is simply {}.

Looking up values

You read a value by giving its key in square brackets:

student = {"name": "Aisha", "age": 15, "grade": "A"}

print(student["name"])   # Aisha
print(student["age"])    # 15

student["name"] finds the key "name" and hands back its value, Aisha. Notice you use the key, not a number — student[0] would not work and would raise an error.

If you ask for a key that doesn't exist, Python raises a KeyError and stops:

print(student["height"])   # KeyError: 'height'

We'll see how to avoid that crash shortly with .get().

Adding and updating

Dictionaries are mutable, meaning you can change them after creation. Assigning to a key either updates it or, if it's new, adds it:

student = {"name": "Aisha", "age": 15}

student["age"] = 16          # update existing key
student["grade"] = "A"       # add a new key
print(student)
# {'name': 'Aisha', 'age': 16, 'grade': 'A'}
  • student["age"] = 16 finds the existing "age" key and replaces 15 with 16.
  • student["grade"] = "A" — since "grade" doesn't exist yet — creates it.

To remove a pair, use del:

del student["grade"]

Safe lookups with .get()

Crashing on a missing key is rarely what you want. The .get() method returns the value if the key exists, or a default you choose if it doesn't — without any error:

student = {"name": "Aisha", "age": 16}

print(student.get("age"))           # 16
print(student.get("height"))        # None
print(student.get("height", 0))     # 0
  • student.get("age") works just like square brackets when the key is present.
  • student.get("height") returns None because there's no such key — but it does not crash.
  • student.get("height", 0) lets you supply a fallback, here 0.

Using .get() is the standard, safe way to read data that might be missing.

Checking if a key exists

You can test for a key with the in keyword, which gives True or False:

student = {"name": "Aisha", "age": 16}

if "age" in student:
    print("We know the age.")
if "height" not in student:
    print("No height recorded.")

This is handy before deciding whether to read or update a key.

Looping over a dictionary

You'll often want to visit every pair. The cleanest way uses .items(), which gives you the key and value together on each pass:

prices = {"apple": 0.50, "bread": 1.20, "milk": 0.90}

for item, cost in prices.items():
    print(f"{item} costs £{cost:.2f}")
  • prices.items() produces each (key, value) pair.
  • for item, cost in ... unpacks that pair into two variables at once: item gets the key, cost gets the value.
  • {cost:.2f} formats the price to two decimal places.

If you only need the keys, loop with for item in prices: (or prices.keys()); for just the values, use prices.values().

Worked example: a word counter

Dictionaries shine at counting. Here's a program that counts how often each word appears in a sentence:

sentence = "the cat sat on the mat the cat purred"
words = sentence.split()        # ['the', 'cat', 'sat', ...]

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

for word, number in counts.items():
    print(f"{word}: {number}")

How it works:

  1. sentence.split() breaks the text into a list of words at the spaces.
  2. counts = {} starts an empty dictionary to tally results.
  3. For each word, counts.get(word, 0) reads its current count — or 0 if we've never seen it — then we add 1 and store it back. This single clever line both creates a new entry the first time and increments it afterwards.
  4. The final loop prints each word with its total.

The output shows the: 3, cat: 2, and the rest at 1. Try writing this with only a list and you'll appreciate how naturally a dictionary fits.

Try it yourself

Build a tiny contact book:

  • Create a dictionary mapping names to phone numbers, e.g. {"Mum": "0700123456"}.
  • Add a new contact by assigning to a new key.
  • Ask the user for a name with input(), then use .get() to print the number or a polite "Not found" message if it's missing.
  • Loop over .items() to print the whole contact book neatly.
  • (Bonus) Store each contact's details as a small dictionary inside the main one, like {"Mum": {"phone": "0700...", "city": "Leeds"}}, and print one person's city.

When you're comfortable, see how dictionaries combine with python functions and parameters — a function that takes a dictionary and returns a summary is a very common, very useful pattern.

Quick quiz

Test yourself and earn XP

How do you write an empty dictionary?

Given `ages = {"Sam": 14}`, how do you read Sam's age?

What does `ages["Lee"] = 12` do if "Lee" is not already a key?

Why use `.get("x", 0)` instead of `["x"]`?

What does `.items()` give you when looping?

FAQ

A list stores items in order and you reach them by a numbered position, like scores[0]. A dictionary stores items as labelled pairs and you reach a value by its key, like scores["maths"]. Use a list for an ordered collection and a dictionary when each value has a meaningful name.

Keys must be unchangeable (immutable) types such as strings, numbers, or tuples. You cannot use a list as a key because lists can change. Values, on the other hand, can be anything: numbers, strings, lists, or even other dictionaries.