Iterating with Dictionaries in Python

Data Science Tool Box Mar 18, 2026

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: or for key in dict.keys() – Iterate over keys
  • for value in dict.values() – Iterate over values
  • for 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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices