Iterating with Dictionaries in Python
Dictionaries are one of the most important data structures in data science. Knowing how to iterate over them efficiently is essential for processing configurations, feature mappings, model results, and JSON-like data.
TL;DR — Best Ways to Iterate Dictionaries
for key in dict:orfor key in dict.keys()– Iterate over keysfor value in dict.values()– Iterate over valuesfor key, value in dict.items()– Iterate over key-value pairs (most common)
1. Basic Dictionary Iteration
config = {
"model_type": "random_forest",
"n_estimators": 200,
"max_depth": 10,
"random_state": 42,
"test_size": 0.2
}
# 1. Iterate over keys only
for key in config:
print(key)
# 2. Iterate over values only
for value in config.values():
print(value)
# 3. Iterate over key-value pairs (most useful)
for key, value in config.items():
print(f"{key:15} : {value}")
2. Real-World Data Science Examples
import pandas as pd
# Example 1: Feature importance dictionary
feature_importance = {
"amount": 0.42,
"quantity": 0.31,
"region": 0.18,
"category": 0.09
}
# Sort by importance
for feature, importance in sorted(feature_importance.items(), key=lambda x: x[1], reverse=True):
print(f"{feature:12} : {importance:.4f}")
# Example 2: Processing model results
model_results = {
"random_forest": {"accuracy": 0.89, "f1": 0.87},
"xgboost": {"accuracy": 0.91, "f1": 0.89},
"lightgbm": {"accuracy": 0.90, "f1": 0.88}
}
for model_name, metrics in model_results.items():
print(f"\nModel: {model_name}")
for metric, value in metrics.items():
print(f" {metric:10} : {value}")
3. Best Practices in 2026
- Prefer
.items()when you need both key and value - Use
.keys()or.values()only when you need just one - Use
sorted(dict.items(), key=...)when you need ordered iteration - Be careful modifying a dictionary while iterating over it
- Use dictionary comprehensions for clean transformations
Looping Over Dictionaries
Looping over a dictionary yields its keys. Use .values() when you only need values and .items() when you need both. Since Python 3.7, dictionaries keep insertion order, so loops are predictable.
Do not add or remove keys while looping; Python raises a RuntimeError. Loop over a copy such as list(d) or build a new dictionary with a comprehension instead.
To sort the output, loop over sorted(d.items(), key=...). This leaves the dictionary unchanged and makes reports easier to read.
Worked Example: Totals, Sorting and Safe Removal
Regional sales totals are printed in order, then small regions are removed safely.
sales = {"North": 1200, "South": 450, "East": 980, "West": 150}
print(sum(sales.values()))
for region, amount in sorted(sales.items(), key=lambda kv: kv[1], reverse=True):
print(f"{region:6} {amount:>6}")
try:
for region in sales:
if sales[region] < 500:
del sales[region]
except RuntimeError as err:
print("RuntimeError:", err)
sales = {"North": 1200, "South": 450, "East": 980, "West": 150}
big = {r: a for r, a in sales.items() if a >= 500}
print(big)
Deleting keys inside the loop raises a RuntimeError about the dictionary changing size. Building a new dictionary with a comprehension keeps only North and East without that problem.
Practical Tips
Dictionaries are also iterable in comprehensions, so {k: v * 2 for k, v in d.items()} builds a transformed copy in one readable line without touching the original.
Dictionary views returned by keys(), values() and items() are live: they reflect later changes to the dictionary without being rebuilt. That makes them cheap to create, but it is also why changing the dictionary during a loop is not allowed.
When you need to accumulate values per key, collections.defaultdict or dict.get with a default keeps the loop short and avoids a KeyError for keys seen for the first time. For counting, collections.Counter is even simpler, because it already knows how to add one to a missing key.
Finally, unpack items directly in the loop header, as in for name, total in totals.items(), so each value has a descriptive name instead of pair[0] and pair[1].
Common Mistakes
- Modifying a dictionary while iterating over it.
- Looping over keys and then looking up each value again.
- Assuming dictionaries are sorted by key.
- Using d.keys() where plain iteration is enough.
Quick Summary
- Iterate keys by default, .values() or .items() as needed.
- Dictionaries keep insertion order.
- Never change size while looping.
- Use sorted() for ordered output.
Conclusion
Iterating over dictionaries is a daily task in data science. In 2026, the most Pythonic and readable way is using for key, value in dict.items(). Combine this with sorting, filtering, or comprehensions when needed. Understanding these patterns will help you write cleaner code when working with configurations, model outputs, feature mappings, and other dictionary-based data structures.
Next steps:
- Review how you currently iterate over dictionaries in your code and improve readability by using
.items()and appropriate sorting