Nishaglobal Education logo

Dictionaries: looking things up by name

Store data as key-value pairs in a Python dictionary, look values up, add and update entries, loop over items, count things, and keep a list of records.

Lesson 11 of 1430 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Create a dictionary and look up values by key
  • Add, change and safely read entries with get()
  • Loop over keys and values, count things, and keep a list of dictionaries
Outline
  1. What you'll learn and why it matters
  2. Creating a dictionary and looking things up
  3. Adding, changing and removing entries
  4. Reading safely with in and get()
  5. Looping over a dictionary
  6. Worked example: counting and totalling
  7. A list of dictionaries
  8. Practice
  9. Common mistakes
  10. Recap
  11. Quiz
  12. Mark lesson complete

What you'll learn and why it matters

A list finds things by position: item 0, item 1. But often you want to find things by name: the price of “tea”, the phone number of “Ravi”, the marks of “Meera”. A dictionary stores pairs of a key (the name you look up) and a value (what you find). Dictionaries are everywhere in real programs, from settings files to data sent between websites.

Creating a dictionary and looking things up

Use curly brackets. Each entry is key: value, and entries are separated by commas:

Python
prices = {"tea": 20, "coffee": 35, "samosa": 15}
print(prices["coffee"])
print(len(prices))
print(prices)

Output

35
3
{'tea': 20, 'coffee': 35, 'samosa': 15}
keyvalue"tea"20"coffee"35"samosa"15prices["coffee"] → 35
A dictionary maps each key to a value. You look up a value by its key, not by its position.

Adding, changing and removing entries

Python
prices = {"tea": 20, "coffee": 35}
prices["samosa"] = 15
prices["tea"] = 25
del prices["coffee"]
print(prices)

Output

{'tea': 25, 'samosa': 15}
CodeWhat happens
prices["samosa"] = 15The key is new, so a new entry is added.
prices["tea"] = 25The key already exists, so its value is replaced.
del prices["coffee"]The entry is removed.

Reading safely with in and get()

Asking for a key that is not there stops the program:

Python
prices = {"tea": 20}
print(prices["juice"])

Python stops with this error

KeyError: 'juice'

Two ways to avoid this:

Python
prices = {"tea": 20, "coffee": 35}
if "juice" in prices:
    print(prices["juice"])
else:
    print("We do not sell juice.")
print(prices.get("juice"))
print(prices.get("juice", 0))

Output

We do not sell juice.
None
0

in checks the keys of a dictionary. get(key) returns None instead of crashing, and get(key, default) returns your default.

Looping over a dictionary

.items() gives you each key and value together, which is usually what you want:

Python
marks = {"Asha": 78, "Ravi": 91, "Meera": 66}
for name, mark in marks.items():
    print(f"{name} scored {mark}")
print("Students:", list(marks.keys()))
print("Top mark:", max(marks.values()))

Output

Asha scored 78
Ravi scored 91
Meera scored 66
Students: ['Asha', 'Ravi', 'Meera']
Top mark: 91

Dictionaries keep entries in the order you added them.

Worked example: counting and totalling

A very common job: count how many times each thing appears, or add up amounts per category. Start with an empty dictionary {} and use get(key, 0) for the first time each key is seen:

Python
spending = [("Food", 850), ("Transport", 500), ("Food", 420), ("Bills", 299), ("Transport", 150)]

totals = {}
for category, amount in spending:
    totals[category] = totals.get(category, 0) + amount

for category, total in totals.items():
    print(f"{category}: {total}")

Output

Food: 1270
Transport: 650
Bills: 299

Each item in spending is a pair in round brackets, called a tuple: a small list that cannot be changed. for category, amount in spending unpacks each pair into two variables. Trace the first two rounds:

Roundcategory, amounttotals afterwards
1"Food", 850{"Food": 850}
2"Transport", 500{"Food": 850, "Transport": 500}
3"Food", 420{"Food": 1270, "Transport": 500}

This exact pattern powers the spending summary in your final project.

A list of dictionaries

Real data is usually many records with the same fields, like rows in a spreadsheet. A list of dictionaries holds that perfectly:

Python
students = [
    {"name": "Asha", "city": "Mumbai", "marks": 78},
    {"name": "John", "city": "London", "marks": 84},
]
students.append({"name": "Li", "city": "Singapore", "marks": 90})

for student in students:
    print(f"{student['name']} ({student['city']}): {student['marks']}")

Output

Asha (Mumbai): 78
John (London): 84
Li (Singapore): 90

Practice

Guided exercise

Phone book

Create a dictionary of three names and phone numbers. Ask the user for a name and print the number, or Not found if the name is not in the phone book.

  1. Create phone_book = {"Asha": "98200 11111", ...}. Store numbers as strings, because you never do maths with them.
  2. Read a name with input().
  3. Use phone_book.get(name, "Not found") and print the result.
Show the solution
Solution
phone_book = {"Asha": "98200 11111", "Ravi": "98450 22222", "Fatima": "50123 3333"}
name = input("Name: ")
print(phone_book.get(name, "Not found"))

Output (you type: Ravi)

Name: Ravi
98450 22222

How to get there: get() returns the number when the key exists and the default text when it does not, so the program never crashes with a KeyError.

Your turn

Count the votes

Given votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"], build a dictionary counting each drink and print it.

Show the solution
Solution
votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"]
counts = {}
for vote in votes:
    counts[vote] = counts.get(vote, 0) + 1
print(counts)

Output

{'tea': 3, 'coffee': 2, 'juice': 1}

How to get there: The same pattern as the spending totals, but adding 1 each time instead of an amount.

Common mistakes

Reading a key that does not exist

You see: KeyError: 'juice'

Fix: Check with if key in d: or use d.get(key, default).

Keys with different capitals or spaces

You see: KeyError: 'tea ' even though tea is there

Fix: Clean input with .strip().lower() before looking it up, and store keys the same way.

Looping with for x in d and expecting values

You see: You get only the keys

Fix: Use d.items() for key and value, or d.values() for values.

Using a list as a key

You see: TypeError: unhashable type: 'list'

Fix: Keys must be values that cannot change, such as strings, numbers or tuples.

Recap

  • A dictionary stores key-value pairs: {"tea": 20}. Look up with d[key].
  • Assigning to a key adds or replaces an entry; del d[key] removes it.
  • Use in or get(key, default) to avoid KeyError.
  • Loop with .items(); count or total per category with d[k] = d.get(k, 0) + amount.

Key terms

Dictionary
A collection of key-value pairs written in curly brackets.
Key
The name you use to look up a value. Each key is unique.
Tuple
An ordered group of values in round brackets that cannot be changed, such as ("Food", 850).

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. `stock = {"pens": 40, "books": 12}`. What is `stock["books"]`?

  2. 2. What does `{"a": 1}.get("b", 0)` return?

  3. 3. After `d = {"x": 1}` and `d["x"] = 5`, what is `d`?

  4. 4. Which loop gives you both the name and the mark from `marks`?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.