Loop Dictionaries
Looping through dictionaries is a fundamental Python skill, because dictionaries store data as key–value pairs.
Python provides multiple clean and efficient ways to loop through keys, values, or both together.
This topic explains all correct ways to loop through dictionaries, from basics to advanced usage.
Loop Through Dictionary Keys (Default)
By default, looping through a dictionary iterates over keys.
python
student = {"name": "Jayesh", "age": 25, "course": "Python"}
for key in student:
print(key)
Loop Through Keys Using keys()
Explicitly looping through keys.
python
for key in student.keys():
print(key)
python
for key in student.keys():
print(key, student[key])
Loop Through Dictionary Values
Use
values() to access only values.python
for value in student.values():
print(value)
Loop Through Key–Value Pairs Using items()
The most common and recommended approach.
python
for key, value in student.items():
print(key, value)
Loop Using Index (Indirect Way)
Dictionaries do not support direct indexing, but you can convert keys to a list.
python
keys = list(student.keys())
for i in range(len(keys)):
print(keys[i], student[keys[i]])
Loop Through Nested Dictionaries
python
students = {
"student1": {"name": "Amit", "age": 20},
"student2": {"name": "Riya", "age": 22}
}
for student_id, info in students.items():
print(student_id)
for key, value in info.items():
print(key, value)
Loop with Condition
python
scores = {"A": 80, "B": 65, "C": 90}
for key, value in scores.items():
if value >= 80:
print(key, value)
Loop and Modify Dictionary Values
Use keys while looping to update values.
python
scores = {"A": 80, "B": 70}
for key in scores:
scores[key] += 5
print(scores)
Loop Using Dictionary Comprehension
python
scores = {"A": 80, "B": 70, "C": 90}
updated = {k: v + 10 for k, v in scores.items()}
print(updated)
Loop Through Dictionary in Sorted Order
python
data = {"b": 2, "a": 1, "c": 3}
for key in sorted(data):
print(key, data[key])
Loop Using enumerate() (Advanced)
python
student = {"name": "Jayesh", "age": 25, "course": "Python"}
for index, (key, value) in enumerate(student.items()):
print(index, key, value)
Common Mistakes
Modifying Dictionary Structure While Looping
python
# for key in student:
# student.pop(key) # RuntimeError
Expecting Index-Based Access
python
# student[0] # TypeError
Best Practices
- Use
items()for key–value loops - Use
keys()orvalues()when only one is needed - Avoid modifying dictionary size during iteration
- Use comprehensions for transformations
- Sort keys if order matters
Summary
- Dictionaries are looped by keys by default
items()is the most powerful loop methodvalues()loops only values- Nested dictionaries require nested loops
- Direct indexing is not supported
- Looping is essential for real-world data handling