Skip to main content

Dictionaries Part 3 — Iteration and Comprehensions

Processing Collections Efficiently

In Lesson 8, you learned how to manipulate dictionaries: adding keys, updating values, deleting entries. Now comes the payoff: processing large collections efficiently. When you have hundreds or thousands of key-value pairs, you need patterns that scale.

This lesson teaches you three iteration methods (.keys(), .values(), .items()), dictionary comprehensions for transforming data, and a brief introduction to nested dictionaries. By the end, you'll build a real-world word frequency counter and temperature conversion system—practical applications that professional developers use daily.


Concept 1: Iterating Over Keys Only

When you want to loop through only the keys in a dictionary, use the .keys() method:

Loading Python environment...

Output:

Alice
Bob
Charlie

Why would you want just keys? When you need to do something with the keys themselves—checking their names, modifying them, or building a new collection from them.

Here's a practical example:

Loading Python environment...

💬 AI Colearning Prompt

"When would you use .keys() vs just iterating for name in grades:? Are they the same thing?"

The short answer: for name in grades: and for name in grades.keys(): do the same thing. Using .keys() is explicit and clearer about intent. Explicit is better than implicit.


Concept 2: Iterating Over Values Only

When you want to loop through only the values (ignoring keys), use .values():

Loading Python environment...

Output:

95
87
92

When would you use this? When you need to analyze the values themselves—calculating averages, finding the highest score, or filtering by value.

Real-world example: calculating class statistics

Loading Python environment...

🚀 CoLearning Challenge

Ask your AI Co-Teacher:

"Given a dictionary of product prices, write code to find the most expensive item and calculate the total inventory value. Which iteration method do you use and why?"

Expected Outcome: You'll recognize that .values() is perfect for price analysis, and you'll understand how built-in functions like sum() and max() work with dictionary values.


Concept 3: Iterating Over Both Keys and Values

The most common pattern: you need both the key and value. Use .items() to get (key, value) pairs:

Loading Python environment...

Output:

Alice: 95
Bob: 87
Charlie: 92

Notice the pattern: for name, grade in grades.items(). This is tuple unpacking. The .items() method returns (key, value) tuples, and Python automatically unpacks them into separate variables.

This is one of Python's most elegant patterns. It reads naturally: "For each name and grade in the dictionary, print them."

Here's a complete inventory example:

Loading Python environment...

Output:

=== Current Inventory ===
apples 50 units
bananas 30 units
oranges 20 units
grapes 15 units

=== Low Stock Alert ===
⚠️ oranges is low: 20 units
⚠️ grapes is low: 15 units

🎓 Expert Insight

In AI-native development, you don't memorize "use .items() for both". You understand: "I need both key and value, so .items() is my tool." The same logic applies to .keys() and .values()—they match your intent. Syntax is cheap; recognizing "I need X from this dictionary" is the skill.


Concept 4: Dictionary Comprehension Syntax

Just like list comprehensions (from Lesson 5), you can transform dictionaries using comprehensions. The syntax is similar:

List comprehension: [expression for item in iterable] Dict comprehension: {key: value for key, value in iterable}

Here's a simple example—doubling all values:

Loading Python environment...

Both approaches produce the same result. The comprehension is more concise and reads like a mathematical set notation: "For each item and price in the dictionary, create a new entry with the doubled price."

💬 AI Colearning Prompt

"Compare the loop version and the comprehension version. Why might the comprehension be preferred even though it's harder to read at first?"

The answer: conciseness and performance. Comprehensions are typically faster (compiled as a single operation) and more readable once you're comfortable with the syntax.


Concept 5: Filtering in Dictionary Comprehensions

Add an if condition to filter entries:

Loading Python environment...

The syntax: {key: value for key, value in iterable if condition}

Practical example: Temperature filtering

Loading Python environment...

✨ Teaching Tip

Use Claude Code to explore comprehension filtering: "Show me 3 different ways to filter dictionaries (with .items() loop, with comprehension, with filter() function). Which is most readable?"


Concept 6: Transforming Keys and Values

You can transform keys, values, or both:

Transform values (Celsius to Fahrenheit):

Loading Python environment...

Transform keys (make them uppercase):

Loading Python environment...

Transform both (swap keys and values):

Loading Python environment...


Concept 7: Introduction to Nested Dictionaries

Sometimes a dictionary's value is itself a dictionary. This is called a nested dictionary:

Loading Python environment...

When would you use nested dictionaries? When you have structured data with multiple attributes. Real-world examples:

  • User profiles (user ID → {name, email, age})
  • API responses (resource → {id, name, description, status})
  • Configuration files (section → {setting1, setting2, setting3})

Iterating nested dictionaries:

Loading Python environment...

Output:

Alice:
age: 20
grade: 95

Bob:
age: 21
grade: 87

🎓 Expert Insight

Nested dictionaries are powerful for organizing complex data. But remember: clarity is essential. If a structure becomes too deeply nested (more than 2-3 levels), consider whether a simpler design exists. In professional code, deeply nested structures often become hard to understand.


Practice Exercises

Exercise 1: Choose the Right Iteration Method

Given this dictionary:

Loading Python environment...

Write code to:

  1. Print all book titles (keys only) — which method?
  2. Calculate total books in inventory (values only) — which method?
  3. Print each book with its count formatted nicely (both) — which method?

Expected output for #3:

The Great Gatsby: 5
1984: 3
To Kill a Mockingbird: 7
Pride and Prejudice: 4

Exercise 2: Dictionary Comprehension — Temperature Conversion

Convert this dictionary of Celsius temperatures to Fahrenheit using a comprehension:

Loading Python environment...

Then, modify it to show only days with temperatures above 70°F using filtering.


Exercise 3: Word Frequency Counter

Given this text, count how many times each word appears:

Loading Python environment...

Challenge: How would you remove punctuation to get cleaner counts?


Common Patterns and Gotchas

Pattern 1: Building a Dictionary from Iteration

Create a new dictionary by transforming data:

Loading Python environment...

Pattern 2: Grouping by Category

Create nested dictionaries for grouped data:

Loading Python environment...

Gotcha 1: Modifying While Iterating

Don't modify a dictionary while looping over it—it can skip items:

Loading Python environment...

Gotcha 2: Readability Over Cleverness

Comprehensions are powerful, but if they become unreadable, use a loop instead:

Loading Python environment...


Real-World Example: Word Frequency Analyzer

Here's a complete example combining iteration, comprehensions, and filtering:

Loading Python environment...

Output:

=== Word Frequency ===
python appears 5 times
is appears 3 times

Total unique words: 15
Words appearing 2+ times: 2

This example uses:

  • .items() to iterate
  • dict comprehension to filter frequent words
  • sorted() to order results (a feature you'll use in real projects)

💬 AI Colearning Prompt

"Walk me through the word frequency analyzer. What does each line do? Why do we use .items() in the sorting step?"


Try With AI

Master dictionary iteration methods and dictionary comprehensions.

🔍 Explore Iteration Methods:

"Show me .keys(), .values(), and .items() with examples. Explain what each returns and when I'd use each (keys-only search, values-only processing, key-value pairs for both)."

🎯 Practice Dict Comprehensions:

"Help me write dict comprehension for temperature conversion: {'New York': 20, 'Los Angeles': 25} to Fahrenheit. Show formula (C*9/5)+32 and add filter for cities above 70°F."

🧪 Test Loop vs Comprehension:

"Debug filtering student grades >= 70: show both for-loop version and dict comprehension. Compare readability. When would I choose loop over comprehension for clarity?"

🚀 Apply to Data Transform:

"Build grade analyzer: iterate over student_grades dict, calculate average, filter passing students, create summary dict. Demonstrate .items() unpacking, comprehension filtering, and safe iteration without modification."