Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Basics

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

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.

A list of three dicts, one per student: Maya 85, Ravi 72, Zoe 91; the loop variable student moves from card to card students = [ ... ] a list of dicts "name": "Maya" "score": 85 "name": "Ravi" "score": 72 "name": "Zoe" "score": 91 student (turn 1) turn 2 turn 3
One card is a dict. The loop hands you one whole card each turn.

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_dict to give pairs. It gives keys; use .items().
  • Unpacking into the wrong number of names. A two-value tuple needs two variables.
  • Setting total = 0 inside the loop. It resets every turn.
  • Keeping your own counter next to a loop. enumerate already does that.

Quick recap

You writeEach turn gives
for k in da key
for v in d.values()a value
for k, v in d.items()a key and its value
for s in studentsone 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 9 of 48

Previous
Python Conditionals and Loops: if/elif/else, for, while, break and continue
Next post
Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults

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.

On this page

  • Looping over a dict gives keys
  • Only the values
  • Keys and values together
  • Tuple unpacking
  • A list of dicts
  • enumerate gives the position
  • zip walks two lists together
  • Building a total and a new list
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.