Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
A dict is one student card and a list of dicts is the stack. Loop over keys, values and items, unpack tuples, use enumerate and zip, and build a total and a pass list for Maya, Ravi and Zoe.
What you will learn
- Loop over a dict's keys, values and items
- Unpack tuples in a for loop
- Go through a list of dicts, and add positions with enumerate or pair two lists with zip
- Build a total and a new list with the start-update-use pattern
Before you start
- Python Conditionals and Loops
- Python Lists, Tuples, Sets and Dicts
So far, loops have gone over simple things like a range of numbers or a short list. Most data doesn't look like that. Think about a stack of student cards. Each card has labels, like name and score, and each label has a value.
In Python, one card is a dict and the whole stack is a list of dicts. So there are two jobs: read across one card, and go through the stack one card at a time.
Looping over a dict gives keys
student = {"name": "Maya", "age": 21, "score": 85}
for key in student:
print(key)
name
age
score
You might expect whole entries, but a for loop over a dict gives you only the keys, in the order you wrote them.
Only the values
student = {"name": "Maya", "age": 21, "score": 85}
for value in student.values():
print(value)
Maya
21
85
The labels are gone. Nothing here says 21 is an age. That's fine when you don't need the labels.
Keys and values together
student = {"name": "Maya", "age": 21, "score": 85}
for key, value in student.items():
print(key, "->", value)
name -> Maya
age -> 21
score -> 85
items() hands out one pair at a time, and each pair is a tuple. With two variables after for, the pair splits: "name" into key, "Maya" into value. The arrow is only text we chose to print. For a dict, this is the one to remember.
Tuple unpacking
That split has a name, tuple unpacking. Slow down on it:
pairs = [("Maya", 85), ("Ravi", 72), ("Zoe", 91)]
for pair in pairs:
print(pair)
for name, score in pairs:
print(name, "scored", score)
('Maya', 85)
('Ravi', 72)
('Zoe', 91)
Maya scored 85
Ravi scored 72
Zoe scored 91
With one variable, the whole tuple lands in it, brackets and quotes included. With two, it splits. You need one variable for each value in the tuple: two values, two names.
A list of dicts
students = [
{"name": "Maya", "score": 85},
{"name": "Ravi", "score": 72},
{"name": "Zoe", "score": 91},
]
for student in students:
print(student["name"], student["score"])
Maya 85
Ravi 72
Zoe 91
On the first turn, student is Maya's whole dict, so student["name"] gives Maya. Then it moves to Ravi's dict, then Zoe's. The print line never changed. It works for three students, and it would work for a much longer list too.
enumerate gives the position
names = ["Maya", "Ravi", "Zoe"]
for i, name in enumerate(names):
print(i, name)
for i, name in enumerate(names, start=1):
print(i, name)
0 Maya
1 Ravi
2 Zoe
1 Maya
2 Ravi
3 Zoe
enumerate wraps the list and hands you a pair each turn: the position and the item. You already know how to split a pair. It starts from 0, like list indexes; people count from 1, so start=1 fixes that. You don't need to keep a counter of your own.
zip walks two lists together
names = ["Maya", "Ravi", "Zoe"]
scores = [85, 72, 91]
for name, score in zip(names, scores):
print(name, score)
Maya 85
Ravi 72
Zoe 91
Here the names are in one list and the scores in another, lined up by position. zip works like a zipper: one item from each list, joined into a pair. If one list is shorter, zip stops when that list runs out.
Building a total and a new list
students = [
{"name": "Maya", "score": 85},
{"name": "Ravi", "score": 72},
{"name": "Zoe", "score": 91},
]
total = 0
passed = []
for student in students:
total = total + student["score"]
if student["score"] >= 80:
passed.append(student["name"])
print("Total:", total)
print("Average:", total / len(students))
print("Passed:", passed)
Total: 248
Average: 82.66666666666667
Passed: ['Maya', 'Zoe']
The total starts at 0 before the loop. Maya makes it 85, Ravi 157, Zoe 248. After the loop, the average is the total divided by 3, and Python shows all the digits it has.
The same pattern builds passed. It starts empty; Maya's 85 passes the check, so her name goes in; Ravi's 72 fails, so append is skipped; Zoe goes in. And the students list hasn't changed at all. You built a new list from it.
The pattern: start before the loop, update inside it, use the answer after it.
Later you'll write the pass list in one line with a comprehension.
Common mistakes
- Expecting
for x in my_dictto give pairs. It gives keys; use.items(). - Unpacking into the wrong number of names. A two-value tuple needs two variables.
- Setting
total = 0inside the loop. It resets every turn. - Keeping your own counter next to a loop.
enumeratealready does that.
Quick recap
| You write | Each turn gives |
|---|---|
for k in d | a key |
for v in d.values() | a value |
for k, v in d.items() | a key and its value |
for s in students | one whole dict |
for i, x in enumerate(xs, start=1) | position and item |
for a, b in zip(xs, ys) | one item from each list |
Try it yourself
Print each student's name with their position, starting from 1, so the first line says 1 Maya.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python for AI: The Five Tools You Actually Need
The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.
Thinking Like a Python Architect in an AI-First World
Coding is laying bricks; architecting is deciding how the pieces fit. A two-line average function shows why someone still has to understand the code an AI tool writes.
Your First Python Program: print, Comments, sep and end
Five tiny files: print and quotes, top-to-bottom order, # comments, several values with sep and end, and the SyntaxError one missing quote causes. Every output is from a real run.
Set Up PyCharm for Python: Install, First Project and First Run
Install PyCharm, create a Pure Python project, and understand the two words that confuse beginners: the interpreter (the cook) and .venv (the project's own shelf). Then run a file and read the exit code.
