🐍 Python for kids · Class 7 · Lesson 4 of 18 · Free
Dictionaries – Look Things Up by Name
⏱ About 30 minutes · ▶ run real Python here — nothing to install · no sign-in
In this lesson you will
- Create a dictionary and read, add, change and delete its entries.
- Loop over a dictionary's keys and values with items().
- Count things with a dictionary, like votes or letters.
In a phone's contacts app you never scroll to "contact number 47". You type a name, like "Mummy", and the number appears. A Python dictionary works the same way: you look up a value by its name, not its position.
What is a dictionary in Python?
A dictionary stores pairs. Each pair has a key and a value, written as key: value.
The whole dictionary goes inside curly brackets { }, with commas between the pairs.
You read a value with its key in square brackets. A list asks "which position?" A dictionary asks "which name?"
▶capital = {"Maharashtra": "Mumbai", "Kerala": "Thiruvananthapuram", "Punjab": "Chandigarh"}2print(capital["Kerala"])3print("States stored:", len(capital))
No variables yet.
▌✏️ Change this code and run it yourself
Thiruvananthapuram States stored: 3
How do I add, change or delete items in a dictionary?
To add a pair, give a new key a value: d[key] = value. If the key already exists, its value is replaced.
So the same line both adds and changes. Keys are unique: one key can never appear twice.
To delete a pair, use del d[key], or pop(key), which also gives the value back.
▶stock = {"pens": 20, "notebooks": 12}2stock["erasers"] = 303stock["pens"] = 184sold = stock.pop("notebooks")5print("Sold notebooks:", sold)6print(stock)
No variables yet.
▌✏️ Change this code and run it yourself
Sold notebooks: 12
{'pens': 18, 'erasers': 30}
How do I avoid a KeyError in a Python dictionary?
Asking for a key that does not exist causes a KeyError. The program stops.
There are two safe ways. Check first with in, or use get(key, default).
get() returns the default when the key is missing, so the program keeps going.
Use in when you want to do something different for a missing key. Use get() when a default answer is enough.
What do you want? chai chai costs 10 rupees Price of idli: not on menu
How do I loop through a dictionary in Python?
A plain for loop over a dictionary gives you the keys, one by one.
items() gives you each key and value together. Write two loop variables: for key, value in d.items().
keys() and values() give only the keys or only the values. values() is handy with sum() and max().
Maths 88 Science 92 English 79 Total: 259 Subjects: ['Maths', 'Science', 'English']
💡 {subject:8} pads the word to 8 characters, so the marks line up in a column.
How do I count things with a dictionary?
Counting is the most useful dictionary trick. Each new item becomes a key, and its value is the count.
For every item, look up its current count with get(item, 0), add one, and store it back.
Here the class votes for a picnic place. The dictionary keeps the score for each place.
The same pattern counts letters in a word, runs per batter, or how often each mark appears.
▶votes = ["Lonavala", "Alibaug", "Lonavala", "Matheran", "Lonavala"]2count = {}3for place in votes:4 count[place] = count.get(place, 0) + 15print(count)6winner = max(count, key=count.get)7print("Winner:", winner)
No variables yet.
▌✏️ Change this code and run it yourself
{'Lonavala': 3, 'Alibaug': 1, 'Matheran': 1}
Winner: Lonavala
💡 max(count, key=count.get) compares the keys by their values and returns the key with the biggest count.
What can a dictionary value be?
A value can be anything: a number, a string, a list, or even another dictionary.
Keys must be things that cannot change, such as strings or numbers. A list cannot be a key.
A dictionary inside a list is a great way to store records, like one dictionary per student.
Read s['marks'] as: from this student's record, take the marks list. Then max() finds the best one.
Isha (Red house) best mark: 92 Dev (Blue house) best mark: 75
🤔 Predict the output
Think like Python: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
d = {"a": 1, "b": 2}
d["a"] = 5
d["c"] = 3
print(d)Question 2. What does this print?
age = {"Ria": 12, "Om": 13}
print(age.get("Sam", 0) + age.get("Om", 0))Question 3. What does this print?
count = {}
for ch in "banana":
count[ch] = count.get(ch, 0) + 1
print(count["a"], len(count))🧩 Your challenge
Build a tiny English-to-Hindi dictionary with at least four words, such as water: paani. Ask the user for 3 words. For each one, print its Hindi meaning, or "not found" if the word is missing. Use get() so the program never crashes.
English word: friend friend -> dost English word: school school -> not found English word: water water -> paani
⚠️ Common mistakes (and how to fix them)
❌ Wrong
fees = {"Class 6": 1500, "Class 7": 1800}
print(fees["Class 8"])KeyError: 'Class 8'
✅ Right
fees = {"Class 6": 1500, "Class 7": 1800}
print(fees.get("Class 8", "no fee listed"))Square brackets crash on a missing key. get() returns a default value instead.
❌ Wrong
marks = {"Maths": 90, "Hindi": 85}
for subject, mark in marks:
print(subject, mark)ValueError: too many values to unpack (expected 2)
✅ Right
marks = {"Maths": 90, "Hindi": 85}
for subject, mark in marks.items():
print(subject, mark)Looping over a dictionary gives only keys. To get key and value together, loop over items().
❌ Wrong
seats = {[1, 2]: "Asha"}TypeError: unhashable type: 'list'
✅ Right
seats = {(1, 2): "Asha"}
print(seats[(1, 2)])A key must not be changeable, and a list can change. Use a tuple (next lesson) or a string as the key.
📌 Remember
- A dictionary stores key: value pairs inside { } and finds values by key.
- d[key] = value adds a new pair or changes an existing one.
- Use in or get(key, default) to avoid a KeyError for missing keys.
- for key, value in d.items() loops over both parts of each pair.
- count[x] = count.get(x, 0) + 1 is the pattern for counting things.
- Values can be lists or dictionaries; keys must be unchangeable, like strings.
Finished the quiz and the challenge?
Questions students ask
What is the difference between a list and a dictionary in Python?
A list finds items by position number, like marks[0]. A dictionary finds values by a key you choose, like marks["Maths"].
Can a Python dictionary have duplicate keys?
No. Each key appears only once. Storing a value under an existing key replaces the old value.
Are dictionaries ordered in Python?
Yes, since Python 3.7. Items stay in the order you added them, and loops follow that order.
How do I check if a key exists in a dictionary?
Use the in keyword, like if "Maths" in marks:. It checks keys, not values.