Lesson 20 of 30 · Collections
Dictionaries
Learn Python dictionaries: store data as key-value pairs, look values up by name, add and update entries and loop through them, with runnable examples.
- 8 min read
- Beginner
- Reviewed
- What a dictionary is and when to use one instead of a list
- How to read, add, change and delete entries
- How to read a key safely when it might be missing
- How to loop through keys and values
Looking things up by name
In a list, you find an item by its position. That is awkward when the position means nothing. Which index holds a person's age? Their city?
A dictionary stores data as key-value pairs. You look a value up by its key, which is usually a meaningful name. It works like a real dictionary: you look up a word (the key) to find its definition (the value).
person = {"name": "Ada", "age": 36, "city": "London"}
print(person["name"])
print(person["age"])A dictionary uses curly brackets. Each entry is written key: value, with commas between entries. Long dictionaries are easier to read on several lines.
course = {
"title": "Python for Beginners",
"lessons": 30,
"free": True,
}
print(course)
print(len(course))Adding and changing entries
Assign to a key. If the key exists, its value is replaced. If it does not, a new entry is created.
person = {"name": "Ada", "age": 36}
person["age"] = 37 # change an existing value
person["city"] = "London" # add a new entry
print(person)Removing entries
person = {"name": "Ada", "age": 36, "city": "London"}
del person["city"]
age = person.pop("age")
print(person)
print("Removed age:", age)When a key might be missing
Asking for a key that does not exist stops the program with a KeyError.
person = {"name": "Ada"}
print(person["email"])There are two safe ways to handle this. Check with in, or use get(), which returns None or a default of your choice instead of raising an error.
person = {"name": "Ada"}
print("email" in person)
print(person.get("email"))
print(person.get("email", "no email on file"))Looping through a dictionary
Looping over a dictionary gives you its keys. Use .items() to get the key and the value together.
prices = {"apple": 30, "banana": 10, "cherry": 120}
for item in prices:
print(item)
print("---")
for item, price in prices.items():
print(f"{item} costs {price}")
print("Total:", sum(prices.values())).keys() gives all the keys and .values() gives all the values.
Counting with a dictionary
A dictionary is ideal for counting things. This program counts how often each word appears.
text = "the cat sat on the mat the end"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)counts.get(word, 0) reads the current count, or 0 if the word has not been seen yet. Adding 1 and storing it back updates the count.
Dictionaries inside lists
Real data is usually a list of dictionaries: one dictionary per record.
students = [
{"name": "Ada", "score": 92},
{"name": "Grace", "score": 85},
{"name": "Alan", "score": 78},
]
for student in students:
if student["score"] >= 80:
print(student["name"], "passed with distinction")Common mistakes
Update the stock of apples, add kiwis, then print the dictionary.
stock = {"apples": 5, "pears": 2}
# 1. Three more apples arrive: add 3 to the apples count
# 2. Add a new item: "kiwis" with a count of 10
# 3. Print the dictionary. Output must be exactly:
# {'apples': 8, 'pears': 2, 'kiwis': 10}
What does person.get("phone", "unknown") return when person has no "phone" key?
Summary
- A dictionary maps keys to values:
{"name": "Ada"}. - Read with
d[key], and safely withd.get(key, default). - Assigning to a key adds or updates an entry.
.items()lets you loop over keys and values together.- A list of dictionaries is the usual shape of real-world data.
You have finished the module on collections. Next, you will learn to package code into reusable functions.
Finished reading? Tick it off to track your progress.