Python – Loop Dictionaries

1. What Does “Loop Dictionaries” Mean?

Looping a dictionary means going through its data one by one.

A dictionary has:

  • Keys

  • Values

  • Key–Value pairs

We can loop through all of them.

2. Loop Through Keys (Default Way)

When you loop directly on a dictionary, you get keys.

Example

student = {
"name": "Amit",
"age": 20,
"city": "Delhi"
}

for key in student:
print(key)

3. Loop Through Values

Use .values() to get all values.

Example

for value in student.values():
print(value)

4. Loop Through Key and Value Together

Use .items() to get both key and value.

Example

for key, value in student.items():
print(key, value)

5. Loop with Condition

Example

marks = {
"math": 80,
"science": 70,
"english": 90
}

for subject, score in marks.items():
if score > 75:
print(subject, score)

6. Loop Using Index (Convert to List)

Dictionaries do not use index numbers,
but we can convert keys to list.

Example

keys = list(student.keys())

for i in range(len(keys)):
print(keys[i], student[keys[i]])

7. Loop Nested Dictionary

Example

data = {
"student1": {"name": "Amit", "age": 20},
"student2": {"name": "Ravi", "age": 22}
}

for key, value in data.items():
print(key)
for k, v in value.items():
print(" ", k, v)

8. Common Beginner Mistakes

❌ Forgetting .items()

for k, v in student:
print(k, v)

❌ Error.

✔ Correct:

for k, v in student.items():

❌ Changing Dictionary While Looping

for k in student:
del student[k]

✔ Correct:

for k in list(student):
del student[k]

9. Simple Practice Examples

Example 1: Print All Keys

product = {"name": "Laptop", "price": 50000}

for key in product:
print(key)

Example 2: Print All Values

for value in product.values():
print(value)

Example 3: Print Key and Value

for k, v in product.items():
print(k, v)

10. Summary (Loop Dictionaries)

✔ Default loop gives keys
✔ Use .values() for values
✔ Use .items() for both
✔ Nested loops work for nested dict
✔ Be careful while modifying

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Dictionary Methods

  • Dictionary Exercises

  • Mini Python Projects

Just tell me 😊

You may also like...