๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 3 ยท Lesson 8 of 15

0% Exit to course

Module 3 ยท Reusable code and honest errors Lesson 8 of 15

Dictionaries โ€” data with names

Learning objective

A dictionary stores labelled values: student = {"name": "Asha", "marks": 72}. It is how one record with several fields is kept together, and it is everywhere in real code and APIs.

The concept

A dictionary stores labelled values: student = {"name": "Asha", "marks": 72}. You read a value by its label, student["marks"], not by its position โ€” which is exactly how a form, a JSON file from an API and a database row are shaped. A list of dictionaries, one per row, is the standard way to hold a whole table in memory.

student.get("email", "not given") returns a default instead of crashing when the key is missing, and for key, value in student.items(): walks the whole record. Counting things is its best trick: counts[name] = counts.get(name, 0) + 1 builds a frequency table in one line, which is how you answer "how many students chose each city".

Python
student = {"name": "Asha", "marks": 72, "city": "Pune"}

print(student["marks"])                    # 72
print(student.get("email", "not given"))   # no crash on a missing key

counts = {}
for city in ["Pune", "Delhi", "Pune"]:
    counts[city] = counts.get(city, 0) + 1
print(counts)                              # {'Pune': 2, 'Delhi': 1}

Common mistakes

The mistake that ends programs is reading a key that is not there: student["email"] on a dictionary without it raises KeyError. Use .get(), or check if "email" in student: first. Also remember that anything treating your keys as positions (student[0]) is a list habit leaking in.

Worked example

student["marks"] returns 72; student.get("email", "not given") returns a default instead of crashing when the key is missing.

Your practice task

Store five students as a list of dictionaries and print a marksheet sorted from highest to lowest.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A dictionary stores labelled values: student = {"name": "Asha", "marks": 72}.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.