Managing Data with Python Dictionaries and Lists
ESTIMATED TIME: 60–90 minutes
SECTION 1: LESSON OVERVIEW
In this lesson, you'll learn how to store, organize, and use data with two super-useful Python tools: lists and dictionaries. These are the building blocks you'll use in real apps — from keeping track of users to storing product info and reading data from websites.
SECTION 2: WHAT YOU'LL LEARN (OBJECTIVES)
By the end, you will be able to:
- Create and use lists to store ordered items.
- Create and use dictionaries to store key-value pairs.
- Add, change, and remove items in lists and dictionaries.
- Loop through lists and dictionaries.
- Combine them (lists of dictionaries and dictionaries of lists).
- Do simple searching, filtering, and sorting.
- Understand how web data (JSON) maps to lists and dictionaries.
SECTION 3: WHY THIS MATTERS (REAL-WORLD)
- Social media apps store posts as lists and each post's details in dictionaries.
- Online stores keep a product catalog as a list of dictionaries.
- Most web APIs send data as JSON, which is basically lists and dictionaries in disguise.
SECTION 4: KEY VOCABULARY
- List: An ordered collection of items, like a numbered shelf. Example:
["apple", "banana", "cherry"] - Index: The position of an item in a list (starts at 0).
- Dictionary: A collection of key-value pairs, like labeled lockers. Example:
{"name": "Alex", "age": 14} - Key: The label in a dictionary ("name", "age").
- Value: The data stored for a key ("Alex", 14).
- JSON: A common data format from the web that looks like Python dictionaries and lists.
SECTION 5: SETUP
- Use Python 3.8 or later.
- You can run code in IDLE, VS Code, Replit, or any online Python editor.
SECTION 6: PART 1 — WORKING WITH LISTS
6.1 Creating and Accessing Lists
Python code:
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple', 'banana', 'cherry']
print(fruits[0]) # 'apple' (first item)
print(fruits[-1]) # 'cherry' (last item)6.2 Changing Items
Python code:
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']6.3 Adding and Removing
Python code:
fruits.append("date") # add to end
print(fruits) # ['apple', 'blueberry', 'cherry', 'date']
fruits.insert(1, "banana") # insert at index 1
print(fruits) # ['apple', 'banana', 'blueberry', 'cherry', 'date']
removed = fruits.pop() # removes and returns last item
print(removed) # 'date'
print(fruits) # ['apple', 'banana', 'blueberry', 'cherry']
fruits.remove("banana") # remove by value (first match)
print(fruits) # ['apple', 'blueberry', 'cherry']6.4 Looping Through a List
Python code:
for fruit in fruits:
print(fruit)6.5 Useful List Functions
Python code:
numbers = [5, 2, 9, 1]
print(len(numbers)) # 4
print(min(numbers)) # 1
print(max(numbers)) # 9
numbers.sort()
print(numbers) # [1, 2, 5, 9]
numbers.reverse()
print(numbers) # [9, 5, 2, 1]Quick Practice — Lists:
- Create a list called
colorswith three colors. - Add one more color.
- Change the second color.
- Loop and print each color.
Try it yourself before checking the next sections!
SECTION 7: PART 2 — WORKING WITH DICTIONARIES
7.1 Creating and Accessing Dictionaries
Python code:
student = {"name": "Maya", "age": 14, "grade": 9}
print(student["name"]) # Maya
print(student["age"]) # 147.2 Adding and Updating
Python code:
student["club"] = "Robotics" # add new key
student["age"] = 15 # update existing key
print(student)7.3 Safe Access with get
Python code:
# get returns None (or a default) if the key is missing
print(student.get("email")) # None
print(student.get("email", "not set")) # 'not set'7.4 Removing Items
Python code:
removed_grade = student.pop("grade") # removes and returns value
print(removed_grade) # 9
print(student)7.5 Looping Through a Dictionary
Python code:
# Loop keys
for key in student.keys():
print("Key:", key)
# Loop values
for value in student.values():
print("Value:", value)
# Loop key-value pairs
for key, value in student.items():
print(key, "->", value)7.6 Merging Dictionaries
Python code:
extra = {"email": "maya@example.com", "age": 16}
student.update(extra) # update merges; later values override earlier ones
print(student)Quick Practice — Dictionaries:
- Make a dictionary
bookwith keys: "title", "author", "pages". - Add a "year" key.
- Update "pages" to a new number.
- Print all keys and values using a loop.
SECTION 8: PART 3 — LISTS + DICTIONARIES TOGETHER
This is where things feel real. You'll often store many similar dictionaries inside a list.
8.1 Example: Product Catalog (List of Dictionaries)
Python code:
products = [
{"id": 101, "name": "Keyboard", "price": 29.99, "in_stock": True},
{"id": 102, "name": "Mouse", "price": 19.99, "in_stock": False},
{"id": 103, "name": "Monitor", "price": 159.99, "in_stock": True},
]
# Print each product name and price
for item in products:
print(item["name"], "-", "$", item["price"])
# Find a product by id
search_id = 102
found = None
for item in products:
if item["id"] == search_id:
found = item
break
if found:
print("Found:", found["name"])
else:
print("Not found")
# Filter items in stock
in_stock_items = []
for item in products:
if item["in_stock"]:
in_stock_items.append(item)
print("In stock count:", len(in_stock_items))8.2 Dictionary of Lists (Grouping)
Python code:
classes = {
"math": ["Ava", "Ben", "Carlos"],
"science": ["Dina", "Eli"],
}
classes["science"].append("Fatima")
print(classes["science"]) # ['Dina', 'Eli', 'Fatima']SECTION 9: SEARCHING, FILTERING, AND SORTING
Python code:
# Filter products cheaper than $50
cheap = []
for p in products:
if p["price"] < 50:
cheap.append(p)
print([p["name"] for p in cheap]) # ['Keyboard', 'Mouse']
# Sort products by price (ascending)
products_sorted = sorted(products, key=lambda p: p["price"])
print([p["name"] for p in products_sorted]) # ['Mouse', 'Keyboard', 'Monitor']SECTION 10: FROM THE WEB TO PYTHON: JSON
APIs on the web often send JSON. In Python, JSON turns into dictionaries and lists.
Python code:
import json
json_text = '''
{
"city": "Springfield",
"forecast": [
{"day": "Mon", "high": 25},
{"day": "Tue", "high": 28}
]
}
'''
data = json.loads(json_text) # JSON string -> Python dict
print(data["city"]) # Springfield
print(data["forecast"][0]["day"]) # Mon
# Turn Python data back into JSON text
print(json.dumps(data, indent=2))SECTION 11: COMMON MISTAKES AND QUICK FIXES
- Using the wrong index
- Issue:
fruits[3]when the list has only 3 items (last index is 2). - Fix: Check
len(fruits)and remember indexes start at 0.
- Issue:
- KeyError in dictionaries
- Issue:
print(student["email"])when "email" doesn't exist. - Fix: Use
student.get("email", "not set")or add the key first.
- Issue:
- Modifying while looping
- Issue: Removing items from a list while iterating can skip items.
- Fix: Build a new list or loop over a copy (
for x in list_name[:]:).
- Mixing data types
- Issue: Sorting a list that mixes numbers and strings may fail.
- Fix: Keep consistent data types in lists.
SECTION 12: GUIDED PRACTICE
12.1 Student Gradebook (List of Dictionaries)
Python code:
gradebook = [
{"name": "Ava", "scores": [88, 92, 95]},
{"name": "Ben", "scores": [75, 85, 79]},
{"name": "Cara", "scores": [100, 98, 97]},
]
# Compute average for each student
for s in gradebook:
total = sum(s["scores"])
count = len(s["scores"])
avg = total / count
s["average"] = round(avg, 1)
# Print report
for s in gradebook:
print(s["name"], "average:", s["average"])
# Find top student
top = None
for s in gradebook:
if (top is None) or (s["average"] > top["average"]):
top = s
print("Top student:", top["name"], "-", top["average"])Expected output (approx):
Ava average: 91.7
Ben average: 79.7
Cara average: 98.3
Top student: Cara - 98.3SECTION 13: MINI PROJECT — SCHOOL CLUB MANAGER
Goal: Manage members, track their roles, and show simple reports using lists and dictionaries.
Requirements:
- Store each member as a dictionary with keys: "id", "name", "role", and "hours".
- Keep all members in a list.
- Add a new member.
- Update hours for a member by id.
- Print a report of all members.
- Show total hours and the member with the most hours.
Starter Code:
Python code:
# 1) Initial data
members = [
{"id": 1, "name": "Maya", "role": "President", "hours": 5},
{"id": 2, "name": "Jon", "role": "Treasurer", "hours": 3},
{"id": 3, "name": "Lia", "role": "Member", "hours": 2},
]
# 2) Add a new member
new_member = {"id": 4, "name": "Zoe", "role": "Member", "hours": 4}
members.append(new_member)
# 3) Update hours for a member by id
def add_hours(member_list, target_id, extra_hours):
for m in member_list:
if m["id"] == target_id:
m["hours"] += extra_hours
return True
return False # id not found
added = add_hours(members, 3, 2) # add 2 hours to id=3
print("Updated:", added)
# 4) Print a report
print("Club Report")
print("-----------")
total_hours = 0
top_member = None
for m in members:
print(f"{m['id']}: {m['name']} ({m['role']}) - {m['hours']} hrs")
total_hours += m["hours"]
if (top_member is None) or (m["hours"] > top_member["hours"]):
top_member = m
print("-----------")
print("Total hours:", total_hours)
print("Top contributor:", top_member["name"], "-", top_member["hours"], "hrs")Expected output (approx):
Updated: True
Club Report
-----------
1: Maya (President) - 5 hrs
2: Jon (Treasurer) - 3 hrs
3: Lia (Member) - 4 hrs
4: Zoe (Member) - 4 hrs
-----------
Total hours: 16
Top contributor: Maya - 5 hrsExtension Ideas:
- List only members with role "Member".
- Sort the report by hours (highest first).
- Save the data to JSON text (
json.dumps) and print it.
SECTION 14: CHECK YOUR UNDERSTANDING (SHORT QUIZ)
- Q1: What index does the first item in a list have?
- Q2: What error happens if you access a missing dictionary key with square brackets?
- Q3: How do you safely access a missing key?
- Q4: Which data structure is best for labeled data: list or dictionary?
- Q5: What Python types do JSON objects and arrays turn into?
SECTION 15: PRACTICE WORKSHEET (TRY IT YOURSELF)
- Task 1: Create a list called
movieswith at least 3 movie titles. Add one, remove one, and print them all. - Task 2: Create a dictionary
userwith keys: "username", "email". Add a new key "is_admin" with False. Print keys and values. - Task 3: Make a list of dictionaries
studentswhere each has "name" and "age". Loop and print "Name — Age". - Task 4: Given products from Section 8, print only the names of products that are in stock.
- Task 5: Sort the products by name and print the sorted names.
SECTION 16: SUMMARY
- Lists store ordered items. Use indexes to access them.
- Dictionaries store key-value pairs. Use keys to access values.
- You can add, update, and remove items from both.
- Loop through lists and dictionaries to process data.
- Combine them to model real-world information.
- Web data (JSON) maps directly to Python dictionaries and lists.
SECTION 17: GLOSSARY QUICK VIEW
- List: Ordered collection like
[1, 2, 3]. - Dictionary: Key-value collection like
{"id": 1, "name": "Sam"}. - Index: Position in a list starting at 0.
- Key: The label in a dictionary to find a value.
- JSON: Web data format similar to Python dictionaries and lists.
END OF LESSON
You did it! You can now model real-world data using Python lists and dictionaries — a key skill for building apps, games, and websites with data.