// 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.
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:
ages = {"Ava": 15, "Leo": 17, "Mia": 16}
print(ages["Leo"]) # 17
If the key doesn’t exist, you get a KeyError:
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:
if "Sam" in ages:
print(ages["Sam"])
print(ages.get("Sam")) # None
print(ages.get("Sam", 0)) # 0
Adding, changing and removing
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:
mia_age = ages.pop("Mia")
print(mia_age) # 16
Looping over a dictionary
By default, looping over a dictionary gives you its keys:
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():
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:
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:
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:
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:
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
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: valuepairs and look values up by key. d[key] = valueboth adds and updates.- Use
inor.get()to avoid aKeyError. - Loop with
.items()to get keys and values together. counts[x] = counts.get(x, 0) + 1is the classic counting pattern.
Things will go wrong sometimes. Learn to handle errors gracefully in Python try and except.