π Python Loop Dictionaries: keys(), values(), items()
π§² Introduction β Why Loop Through Dictionaries?
Dictionaries are unordered key-value stores, and one of the most common tasks is to iterate through them to process data, display values, or perform conditional operations.
Python provides elegant looping mechanisms using .keys()
, .values()
, and .items()
to access keys, values, or both at once.
π― In this guide, youβll learn:
- How to loop through dictionary keys, values, and items
- Real-world use cases for each iteration style
- Best practices for clean and efficient loops
π 1. Looping Through Dictionary Keys
person = {"name": "Alice", "age": 30, "job": "Engineer"}
for key in person:
print(key)
β Explanation:
- By default, looping through a dictionary iterates over its keys.
- Output:
name age job
β
Explicit .keys()
(Same as Above)
for key in person.keys():
print(key)
β Note: Functionally the same, but more readable and explicit.
π¦ 2. Looping Through Dictionary Values
for value in person.values():
print(value)
β Explanation:
- Iterates through all values:
"Alice"
,30
,"Engineer"
π 3. Looping Through Key-Value Pairs with .items()
for key, value in person.items():
print(f"{key}: {value}")
β Explanation:
items()
returns tuples:("name", "Alice")
, etc.- Tuple unpacking assigns
key
andvalue
.
π§ Real-World Example: Counting Occurrences
counts = {"apple": 3, "banana": 5, "cherry": 2}
for fruit, quantity in counts.items():
print(f"{fruit.title()} - Quantity: {quantity}")
β Explanation:
- Practical in eCommerce, analytics, or form data parsing.
π Bonus: Loop Through Sorted Keys
for key in sorted(person.keys()):
print(f"{key}: {person[key]}")
β Explanation:
- Ensures consistent order when order matters.
π‘ Best Practices
- β
Use
.items()
when you need both keys and values. - β
Use
.values()
only when keys are not needed. - β Sort keys if consistent order is required (for logs or reports).
- β Avoid modifying the dictionary while iterating.
π Summary β Recap & Next Steps
Looping through a dictionary gives you full control over its contentsβwhether you’re filtering data, transforming values, or preparing outputs. Python’s for
loop combined with dictionary view methods makes iteration clean and powerful.
π Key Takeaways:
- β
Use
for key in dict:
or.keys()
to iterate through keys. - β
Use
.values()
to iterate through just the values. - β
Use
.items()
to access both key and value in each iteration. - β Sort keys if predictable output is needed.
βοΈ Real-World Relevance:
Used in API responses, form data processing, user settings, shopping carts, and configuration files.
β FAQ Section β Python Loop Dictionaries
β How do I loop through a dictionary?
β Use:
for key in mydict:
print(key)
β How do I loop through both key and value?
β Use:
for key, value in mydict.items():
print(key, value)
β Can I modify a dictionary while looping through it?
β οΈ Avoid modifying a dictionary while iterating. Use dict.copy()
if needed.
β Is dictionary iteration ordered?
β Yes, in Python 3.7+, dictionaries maintain insertion order.
β How do I loop through sorted dictionary keys?
β Use:
for key in sorted(mydict):
print(key, mydict[key])
Share Now :