Iterating with Dictionaries in Python – Best Practices for Data Science 2026
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"
Model: {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
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