Dictionaries
A dictionary stores data as key–value pairs. Instead of finding a value by its position, you look it up by a meaningful key, just as you look up a word in a real dictionary to find its meaning. Dictionaries are everywhere in Python, from student records to data loaded from the web.
Creating a dictionary
Write pairs inside curly braces as key: value, separated by commas. Keys are usually strings; values can be anything.
student = {
"name": "Amina",
"age": 20,
"course": "Computer Science",
}
print(student)
print(student["name"])
print(len(student))
Each key must be unique; if you repeat a key, the later value replaces the earlier one. Since Python 3.7, dictionaries remember the order in which keys were added. You can also create one with dict(name="Amina", age=20), or start empty with {}.
student["age"] follows the arrow from "age" and gives 20.Reading values safely
Square brackets fetch a value by its key, but a missing key raises an error. The get() method returns None, or a default you choose, instead.
student = {"name": "Amina", "age": 20}
print(student.get("age"))
print(student.get("phone"))
print(student.get("phone", "not given"))
student["phone"] on a dictionary without that key stops the program with KeyError: 'phone'. Use get(), or check first with if "phone" in student:. Note that in checks keys, not values.
Adding, changing and removing
Assigning to a key updates it if it exists and adds it if it doesn't.
student = {"name": "Amina", "age": 20, "course": "Computer Science"}
student["age"] = 21 # change
student["county"] = "Mombasa" # add
print(student)
del student["course"] # delete
county = student.pop("county") # delete and return the value
print(county)
print(student)
update() changes or adds several pairs at once:
prices = {"tea": 30, "mandazi": 10, "chapati": 20}
prices.update({"tea": 35, "samosa": 25})
print(prices)
"tea" keeps its original position but gets the new price; "samosa" is added at the end.
Looping through a dictionary
The methods keys(), values() and items() give you views of the keys, the values or the pairs. Looping over items() and unpacking each pair is the most common pattern.
prices = {"tea": 30, "mandazi": 10, "chapati": 20}
for item, price in prices.items():
print(f"{item}: KES {price}")
print(list(prices.keys()))
print(sum(prices.values()))
print("tea" in prices, 30 in prices)
Looping directly over a dictionary (for item in prices:) gives you the keys. And 30 in prices is False because 30 is a value, not a key; use 30 in prices.values() to search values.
Adding or deleting keys while looping over the same dictionary raises RuntimeError: dictionary changed size during iteration. Loop over a copy, such as list(prices), if you need to remove items as you go.
Counting with a dictionary
A classic use is counting how often things appear. get(word, 0) returns the current count, or 0 the first time a word is seen.
votes = "yes no yes yes maybe no"
counts = {}
for vote in votes.split():
counts[vote] = counts.get(vote, 0) + 1
print(counts)
Nested dictionaries
A value can be another dictionary (or a list). This lets you model records within records, like a class register keyed by admission number.
students = {
"S001": {"name": "Amina", "score": 78},
"S002": {"name": "Brian", "score": 64},
}
students["S002"]["score"] = 70 # update a nested value
for adm_no, info in students.items():
print(adm_no, info["name"], info["score"])
This shape, dictionaries and lists nested inside each other, is exactly what JSON data from websites looks like. You'll work with it on Working with CSV & JSON.
Rules for keys
- Keys must be immutable (hashable): strings, numbers and tuples work; lists and dictionaries don't.
- Keys are unique, but values can repeat.
- A tuple key can combine several pieces of information, for example
distances[("Nairobi", "Nakuru")].
Key points
- Dictionaries map unique keys to values and keep insertion order.
d[key]raisesKeyErrorif the key is missing;d.get(key, default)doesn't.- Assign to add or change, and use
del,pop()orupdate()to edit. - Loop with
items();inchecks keys, not values. - Nest dictionaries and lists to represent structured records.
Tip: use the ← and → keys to move between pages.
