Creating and Looping Through Dictionaries in Python – Comprehensive Guide for Data Science 2026

Datatypes Mar 19, 2026

Creating and Looping Through Dictionaries in Python – Comprehensive Guide for Data Science 2026

Dictionaries are one of the most essential data structures in Python data science. They store data as key-value pairs, enabling fast lookups, flexible configurations, feature mapping, model parameters, and summary statistics. Mastering how to create and loop through dictionaries will make your code cleaner, faster, and more professional.

TL;DR — Key Techniques

  • Create with literal {}, dict(), zip(), or dict comprehensions
  • Loop with .items() for key-value pairs (most common)
  • Use .keys() or .values() when you need only one side
  • Modern Python guarantees insertion order

1. Creating Dictionaries

# 1. Literal syntax
feature_importance = {
    "amount": 0.42,
    "quantity": 0.31,
    "profit": 0.18,
    "region": 0.09
}

# 2. From two lists using zip (very common)
features = ["amount", "quantity", "profit"]
scores = [0.42, 0.31, 0.18]
importance = dict(zip(features, scores))

# 3. Dict comprehension
squared_importance = {k: v ** 2 for k, v in feature_importance.items()}

2. Looping Through Dictionaries

# Most common and recommended
for feature, score in feature_importance.items():
    print(f"{feature:12} : {score:.4f}")

# Only keys
for feature in feature_importance.keys():
    print(feature)

# Only values
for score in feature_importance.values():
    print(score)

# With enumerate for ranked output
for rank, (feature, score) in enumerate(feature_importance.items(), start=1):
    print(f"#{rank:2d} {feature:12} : {score:.4f}")

3. Real-World Data Science Examples

import pandas as pd

# Small inline sample so this example runs as-is.
# In a real project you would load it: df = pd.read_csv("sales_data.csv")
df = pd.DataFrame({
    "customer_id": [101, 102, 103, 104, 105, 106],
    "customer_name": ["Ana", "Ben", "Chen", "Dana", "Eli", "Fay"],
    "order_date": ["2026-01-05", "2026-01-12", "2026-02-03",
                   "2026-02-18", "2026-03-01", "2026-03-09"],
    "amount": [1250.75, 890.50, 2340.00, 1780.25, 2615.40, 450.00],
    "quantity": [3, 2, 5, 4, 6, 1],
    "profit": [312.69, 222.63, 585.00, 445.06, 653.85, 112.50],
    "region": ["North", "South", "East", "North", "West", "South"],
    "category": ["Electronics", "Books", "Electronics", "Home", "Home", "Books"],
    "rating": [5, 4, None, 3, 5, 4],
})

# Example 1: Column mapping dictionary
col_mapping = {col: col.lower().replace(" ", "_") for col in df.columns}

# Example 2: Model configuration
model_config = {
    "model_type": "random_forest",
    "n_estimators": 200,
    "max_depth": 10,
    "random_state": 42
}

for key, value in model_config.items():
    print(f"{key:15} = {value}")

# Example 3: Summary statistics per group
summary = {}
for region, group in df.groupby("region"):
    summary[region] = {
        "total_sales": group["amount"].sum(),
        "avg_amount": round(group["amount"].mean(), 2),
        "count": len(group)
    }

for region, stats in summary.items():
    print(f"{region}: {stats}")

4. Best Practices in 2026

  • Use dict comprehensions for clean creation from iterables
  • Always loop with .items() when you need both key and value
  • Use .get(key, default) for safe access
  • Keep configuration and hyperparameters as dictionaries
  • Prefer collections.defaultdict when you need automatic defaults

Views: keys(), values() and items()

The three methods return view objects, not copies. A view reflects later changes to the dictionary, costs almost nothing to create, and can be looped over directly. Key and item views also support set operations, so d1.keys() & d2.keys() finds shared keys without building extra sets.

Because dictionaries keep insertion order, loops visit entries in the order they were added. To loop in a different order, sort the items explicitly — for example by value with sorted(d.items(), key=lambda kv: kv[1]).

Worked Example: Building a Dict From Rows and Reporting It

rows = [
    ("North", 1250.75), ("South", 890.50), ("North", 2340.00),
    ("East", 1780.25), ("South", 450.00),
]

# Build: total per region
totals = {}
for region, amount in rows:
    totals[region] = totals.get(region, 0.0) + amount

# Loop sorted by value, largest first
for rank, (region, total) in enumerate(
        sorted(totals.items(), key=lambda kv: kv[1], reverse=True), start=1):
    print(f"#{rank} {region:6} {total:>10,.2f}")

# Views are live
keys = totals.keys()
totals["West"] = 0.0
print("West" in keys)                      # True

# Shared keys between two dicts
targets = {"North": 3000, "West": 500}
print(totals.keys() & targets.keys())    # {'North', 'West'} (order may vary)

# Safe modification while looping: iterate over a copy
for region in list(totals):
    if totals[region] == 0:
        del totals[region]
print(totals)

Common Mistakes

  • Looping over the dict and expecting pairs: for x in d gives keys only; use .items()
  • Deleting keys during iteration: iterate over list(d) instead
  • Indexing a view: d.keys()[0] fails; use next(iter(d)) or list(d)[0]
  • Calling dict(zip(a, b)) on lists of different lengths: extra items are dropped silently

Quick Summary

  • Create dicts with literals, dict(zip(...)) or comprehensions
  • Loop with .items(); sort the items when you need a different order
  • Views are live and support set-style operations on keys

Conclusion

Creating and looping through dictionaries is a fundamental skill every data scientist uses daily. In 2026, dictionaries power feature mapping, model configuration, summary statistics, and clean data processing pipelines. Mastering literal creation, zip(), dict comprehensions, and .items() looping will make your code significantly more Pythonic, readable, and efficient.

Next steps:

  • Review your current code and replace manual key-value handling with clean dictionary creation and .items() loops

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