- Iterating over keys — using keys() and direct iteration
- Iterating over values — using values() method
- Iterating over key-value pairs — using items() method
- Ordered iteration — sorting and ordered iteration
- Filtering — filtering during iteration
- Modifying dictionaries — safe modification during iteration
- Common mistakes — and how to avoid them
Introduction to Dictionary Iteration
Iteration is the process of accessing each element in a collection sequentially. In Python, dictionaries are iterable objects, but the iteration behavior is different from lists and tuples. Since dictionaries store key-value pairs, you can iterate over keys, values, or both.
The key characteristics of dictionary iteration are:
- Keys iteration — iterating over keys using
keys()or directly - Values iteration — iterating over values using
values() - Items iteration — iterating over key-value pairs using
items() - Order preservation — Python 3.7+ preserves insertion order
💡 Key concept: Dictionaries are optimized for key lookups, not for iteration. However, iteration over dictionaries is still efficient and commonly used.
Iterating Over Keys
Accessing All Keys
You can iterate over dictionary keys using the keys() method or by iterating directly over the dictionary.
# Direct iteration (iterates over keys)
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key in person:
print(f"Key: {key}")
# Output:
# Key: name
# Key: age
# Key: city
# Using keys() method (explicit)
for key in person.keys():
print(f"Key: {key}")
# Converting keys to a list
keys_list = list(person.keys())
print(keys_list) # ['name', 'age', 'city']
# Iterating and accessing values
for key in person:
print(f"{key}: {person[key]}")
# Checking keys during iteration
for key in person:
if key == "age":
print(f"Found age key with value: {person[key]}")
Characteristics:
- Direct iteration over a dictionary iterates over keys
keys()method is explicit and readable- Order is preserved (Python 3.7+)
- Useful for checking key existence
Quick Check: What does direct iteration over a dictionary return? (Answer: Keys)
Iterating Over Values
Accessing All Values
The values() method provides a view of all values in the dictionary, which can be iterated over.
# Iterating over values
person = {"name": "Alice", "age": 25, "city": "NYC"}
for value in person.values():
print(f"Value: {value}")
# Output:
# Value: Alice
# Value: 25
# Value: NYC
# Converting values to a list
values_list = list(person.values())
print(values_list) # ['Alice', 25, 'NYC']
# Calculating sum of numeric values
scores = {"math": 85, "science": 92, "english": 78}
total = sum(scores.values())
print(f"Total score: {total}") # 255
# Finding maximum value
max_score = max(scores.values())
print(f"Highest score: {max_score}") # 92
# Filtering values
for score in scores.values():
if score >= 80:
print(f"Good score: {score}")
Characteristics:
values()returns a view of all values- Order is preserved (Python 3.7+)
- Can contain duplicate values
- Useful for performing operations on values
Quick Check: Can values() contain duplicate values? (Answer: Yes, because values are not required to be unique)
Iterating Over Key-Value Pairs
Accessing Both Keys and Values
The items() method is the most commonly used method for iterating over dictionaries. It returns key-value pairs as tuples.
# Iterating over items
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key, value in person.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
# city: NYC
# Using items() in comprehensions
scores = {"math": 85, "science": 92, "english": 78}
passed = {subject: score for subject, score in scores.items() if score >= 80}
print(passed) # {'math': 85, 'science': 92}
# Iterating and modifying values
for key, value in scores.items():
print(f"{key}: {value + 5}") # Adding 5 to each score
# Unpacking items
for subject, score in scores.items():
if score >= 90:
print(f"{subject}: Excellent!")
# Using items() with enumerate
for i, (key, value) in enumerate(scores.items()):
print(f"{i+1}. {key}: {value}")
Characteristics:
items()returns a view of (key, value) tuples- Most common and Pythonic way to iterate
- Allows unpacking in the loop
- Order is preserved (Python 3.7+)
Quick Check: What does items() return when iterated? (Answer: (key, value) tuples)
Ordered Iteration
Iterating in a Specific Order
In Python 3.7+, dictionaries preserve insertion order. You can also use sorted() to iterate in a custom order.
# Insertion order is preserved
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key in person:
print(key) # name, age, city
# Iterating in sorted order (by keys)
scores = {"math": 85, "science": 92, "english": 78}
for subject in sorted(scores.keys()):
print(f"{subject}: {scores[subject]}")
# english: 78
# math: 85
# science: 92
# Iterating in reverse order
for key in reversed(list(person.keys())):
print(f"{key}: {person[key]}")
# city: NYC
# age: 25
# name: Alice
# Sorting by values
scores = {"math": 85, "science": 92, "english": 78}
for subject, score in sorted(scores.items(), key=lambda item: item[1]):
print(f"{subject}: {score}")
# english: 78
# math: 85
# science: 92
# Sorting by values (descending)
for subject, score in sorted(scores.items(), key=lambda item: item[1], reverse=True):
print(f"{subject}: {score}")
# science: 92
# math: 85
# english: 78
Characteristics:
- Python 3.7+ preserves insertion order
- Use
sorted()for custom ordering - Use
reversed()for reverse order - Sorting by values requires
items()andkeyparameter
Quick Check: Does Python 3.7+ preserve dictionary order? (Answer: Yes — insertion order is preserved)
Filtering During Iteration
Iterating with Conditions
You can filter dictionary items during iteration using conditional statements or comprehensions.
# Using if statements
scores = {"math": 85, "science": 92, "english": 78}
for subject, score in scores.items():
if score >= 80:
print(f"Passing: {subject} - {score}")
# Using dictionary comprehension
passed = {subject: score for subject, score in scores.items() if score >= 80}
print(passed) # {'math': 85, 'science': 92}
# Filtering keys
person = {"name": "Alice", "age": 25, "city": "NYC", "email": "alice@example.com"}
for key in person:
if key.startswith('a'):
print(f"{key}: {person[key]}")
# Filtering values
for key, value in person.items():
if isinstance(value, str):
print(f"String: {key} -> {value}")
# Complex filtering
for subject, score in scores.items():
if score >= 85 and subject.startswith('s'):
print(f"{subject}: {score}")
Methods:
- Conditional statements — iterate with if conditions
- Dictionary comprehension — create filtered dictionaries
- Key filtering — filter by key properties
- Value filtering — filter by value properties
Modifying Dictionaries During Iteration
Safe Modification Techniques
Modifying a dictionary during iteration can cause errors. Here are safe ways to do it.
# WRONG — modifies during iteration (raises RuntimeError)
scores = {"math": 85, "science": 92, "english": 78}
# for subject in scores:
# if scores[subject] < 80:
# del scores[subject] # RuntimeError: dictionary changed size during iteration
# CORRECT — iterate over a copy of keys
scores = {"math": 85, "science": 92, "english": 78}
for subject in list(scores.keys()):
if scores[subject] < 80:
del scores[subject]
print(scores) # {'math': 85, 'science': 92}
# CORRECT — create a new dictionary
scores = {"math": 85, "science": 92, "english": 78}
filtered = {k: v for k, v in scores.items() if v >= 80}
print(filtered) # {'math': 85, 'science': 92}
# CORRECT — using a list of keys to remove
to_remove = [subject for subject, score in scores.items() if score < 80]
for subject in to_remove:
del scores[subject]
print(scores) # {'math': 85, 'science': 92}
# Updating values during iteration (safe)
scores = {"math": 85, "science": 92, "english": 78}
for subject in scores:
scores[subject] += 5 # Safe — updating values doesn't change size
print(scores) # {'math': 90, 'science': 97, 'english': 83}
Guidelines:
- Iterate over a copy —
list(dict.keys()) - Use comprehension — create a new dictionary
- Collect keys to remove — then remove after iteration
- Updating values — safe during iteration
Quick Check: What happens if you modify a dictionary during iteration? (Answer: RuntimeError: dictionary changed size during iteration)
Common Mistakes
Watch Out For These!
Mistake 1: Modifying Dictionary During Iteration
# WRONG — raises RuntimeError
scores = {"math": 85, "science": 92, "english": 78}
# for subject in scores:
# if scores[subject] < 80:
# del scores[subject] # RuntimeError
# CORRECT — iterate over a copy
for subject in list(scores.keys()):
if scores[subject] < 80:
del scores[subject]
Mistake 2: Forgetting .items() When Unpacking
# WRONG — iterating over keys only
person = {"name": "Alice", "age": 25}
# for key, value in person: # ValueError: too many values to unpack
# CORRECT — use items()
for key, value in person.items():
print(f"{key}: {value}")
Mistake 3: Assuming Order in Older Python Versions
# WRONG — order is not guaranteed in Python 3.6 and earlier
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
print(key) # Order may vary
# CORRECT — use OrderedDict if order is critical
from collections import OrderedDict
ordered = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
for key in ordered:
print(key) # a, b, c
Quick Check: What is the most common mistake when iterating over dictionaries? (Answer: Modifying the dictionary during iteration)
Interactive Editor
Experiment with dictionary iteration techniques directly in your browser. Modify the code and see the results in real time.
DICTIONARY ITERATION PRACTICE
========================================
Person: {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com'}
Scores: {'math': 85, 'science': 92, 'english': 78}
1. ITERATING OVER KEYS
Key: name
Key: age
Key: city
Key: email
2. ITERATING OVER VALUES
Value: Alice
Value: 25
Value: NYC
Value: alice@example.com
3. ITERATING OVER ITEMS
name: Alice
age: 25
city: NYC
email: alice@example.com
4. ORDERED ITERATION
english: 78
math: 85
science: 92
5. FILTERING
Passing: math - 85
Passing: science - 92
6. DICTIONARY COMPREHENSION
Filtered scores: {'math': 85, 'science': 92}
Dictionary iteration practice complete!
Certificate of Completion
You have completed the Python Dictionary Iteration tutorial. You understand iterating over keys, values, items, ordered iteration, filtering, and modifying dictionaries during iteration.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about dictionary iteration:
Frequently Asked Questions
What is the most Pythonic way to iterate over a dictionary?
for key, value in dict.items(): when you need both keys and values. Use for key in dict: when you only need keys.
Can I modify a dictionary while iterating over it?
for key in list(dict.keys()):.
Does dictionary iteration preserve order?
OrderedDict if order is critical.
How do I iterate over a dictionary in sorted order?
sorted(): for key in sorted(dict.keys()): for keys, or for key, value in sorted(dict.items()): for both keys and values.
What is the difference between keys(), values(), and items()?
keys() returns only keys, values() returns only values, and items() returns key-value pairs as tuples. All return view objects that reflect changes to the dictionary.
How do I filter a dictionary during iteration?
{k: v for k, v in dict.items() if condition}, or use a loop with an if statement and collect items to keep.
Where to Go From Here
After mastering dictionary iteration, consider exploring these related topics:
Formatting Dictionaries
Learn how to format and display dictionaries effectively.
Learn More →Nested Dictionaries
Work with dictionaries within dictionaries.
Learn More →Dictionary Comprehension
Create dictionaries concisely using comprehension syntax.
Learn More →