🔁 How to Loop Through a Python Dictionary | TechTown.in
Dictionaries in Python are used to store data as key-value pairs, and one of the most powerful things you can do is loop through them.
Whether you’re displaying user data, filtering values, or exporting records — looping through a dictionary gives you full control over its contents.
Let’s explore all the ways to iterate over a Python dictionary — keys, values, and both!
📦 Sample Dictionary
person = {
"name": "Tanmay",
"age": 22,
"city": "Jaipur"
}
🔹 Loop Through Keys Only
By default, looping through a dictionary gives you the keys:
for key in person:
print(key)
Or, explicitly:
for key in person.keys():
print(key)
🎯 Output:
name
age
city
🔸 Loop Through Values Only
Use .values() to access just the values:
for value in person.values():
print(value)
🎯 Output:
Tanmay
22
Jaipur
🔁 Loop Through Key-Value Pairs
Use .items() to loop through both keys and values:
for key, value in person.items():
print(f"{key}: {value}")
🎯 Output:
name: Tanmay
age: 22
city: Jaipur
🧠 Real-Life Example: Display Product Details
product = {
"id": 101,
"name": "Laptop",
"price": 59999,
"in_stock": True
}
for key, value in product.items():
print(f"{key.upper()} → {value}")
✅ Great for dashboards, logs, and API data display.
📊 Filter Values While Looping
for key, value in product.items():
if isinstance(value, int):
print(f"{key}: {value}")
🎯 Only prints numeric values — useful for filtering!
📝 Summary – Dictionary Loop Methods
| Loop Type | Syntax | Use Case |
|---|---|---|
| Loop through keys | for key in dict: | Default loop |
| Loop through keys | for key in dict.keys() | Explicit key access |
| Loop through values | for value in dict.values() | Value-only iteration |
| Loop through items | for key, value in dict.items() | Most common full iteration |
🏁 Final Thoughts
Looping through a Python dictionary gives you complete control over your data. Whether you’re processing inputs, displaying formatted output, or cleaning data — these loop patterns are essential for real-world Python development.
✅ Learn them once, and use them everywhere — from backend logic to front-end rendering and beyond.
📘 Continue mastering Python with us at TechTown.in

