A dictionary stores data as key–value pairs, like a real dictionary maps a word (key) to its meaning (value). Instead of looking things up by position (index 0, 1, 2…), you look them up by a meaningful name. It's one of the most useful structures in all of programming — and we'll finish by building a Student Result Manager with it.
1Key-value pairs
A dictionary uses curly braces, with each item written as key: value, separated by commas. You access a value by its key (not a number):
student = {"name": "Asha", "age": 16, "grade": "A"}
print(student["name"]) # Asha
student["age"] = 17 # change a value
student["city"] = "Delhi" # add a new pair
print(student)Click Run to execute.
- A dictionary stores key–value pairs in curly braces; you look up values by key, not index.
- Keys must be unique and immutable (string, number, tuple — not a list).
- Dictionaries are mutable: add/change a pair with
d[key] = value.
2Dictionary methods and looping
| Method | Does |
|---|---|
keys() | All the keys |
values() | All the values |
items() | All key-value pairs (great for looping) |
get(key) | Value for key, or None if absent (no error) |
update(d2) | Merge in another dictionary |
clear() | Empty the dictionary |
get(key) instead of d[key] when a key might not exist — d["x"] crashes with an error if 'x' is missing, but d.get("x") safely returns None.Looping over a dictionary with items() gives you each key and value together:
Click Run to execute.
- keys(), values(), items() return the keys, values, and pairs; items() is ideal for looping.
get(key)safely returns None for a missing key;d[key]raises an error.- update() merges another dict; clear() empties it.
3Project: Student Result Manager
Dictionaries are perfect for records. This Student Result Manager stores a student's subject marks, then computes their total, average and grade. Run it, then add a subject or change the marks:
Click Run to execute.
- Dictionaries naturally model a record (a student, with named fields).
- Read values by key, then compute totals/averages from them.
- round(value, 2) rounds a number to 2 decimal places for a tidy average.
★ Project: extend the Result Manager
Using the playground above:
- Add two more subjects to the dictionary and update the total/average to include them.
- Use a for loop over items() to print each subject and its mark.
- Use get() to safely look up a subject that might not be there.
- Bonus: store several students (a list of dictionaries) and print each one's average.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.