Dictionary Comprehensions in Python

Data Science Tool Box Mar 18, 2026

Dictionary Comprehensions in Python

Dictionary comprehensions provide a clean, Pythonic way to create dictionaries from iterables. They are extremely useful in data science for building feature mappings, configuration objects, result summaries, and transforming column names or metadata.

TL;DR — Basic Syntax

  • {key_expr: value_expr for item in iterable if condition}
  • Similar to list comprehensions but produces a dict
  • Supports both filtering and conditional value assignment

1. Basic Dictionary Comprehensions

scores = {"Alice": 85, "Bob": 92, "Charlie": 78, "Diana": 95}

# Simple transformation
upper_scores = {name.upper(): score for name, score in scores.items()}

# With filtering
high_scores = {name: score for name, score in scores.items() if score >= 90}

print(high_scores)

2. Real-World Data Science Examples

import pandas as pd

# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
    "order_id": range(1001, 1001 + n),
    "order_date": pd.date_range("2026-01-01", periods=n, freq="3D"),
    "customer_id": rng.integers(101, 121, n),
    "customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
    "product_id": rng.integers(1, 9, n),
    "region": rng.choice(["North", "South", "East", "West"], n),
    "category": rng.choice(["Electronics", "Computers", "Books", "Home"], n),
    "payment_method": rng.choice(["card", "cash", "wallet"], n),
    "segment": rng.choice(["consumer", "business"], n),
    "quantity": rng.integers(1, 6, n),
    "amount": rng.uniform(50, 2500, n).round(2),
    "discount": rng.choice([0.0, 0.05, 0.1, 0.2], n),
}).assign(
    price=lambda d: (d["amount"] / d["quantity"]).round(2),
    profit=lambda d: (d["amount"] * rng.uniform(0.05, 0.3, n)).round(2),
).assign(
    ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
    status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)

df = pd.read_csv("sales_data.csv")

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

# Example 2: Feature importance dictionary
feature_importance = {
    col: round(importance, 4) 
    for col, importance in zip(df.columns, [0.42, 0.31, 0.18, 0.09])
    if importance > 0.05
}

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

3. Advanced Patterns with Conditionals

# Conditional value
categorized = {
    name: "High" if score >= 90 else "Medium" if score >= 75 else "Low"
    for name, score in scores.items()
}

# Using enumerate for indexed keys
indexed_features = {f"feature_{i}": name for i, name in enumerate(df.columns)}

4. Best Practices in 2026

  • Use dictionary comprehensions for clean, one-line transformations
  • Keep the key and value expressions simple and readable
  • Use them to build mapping dictionaries, metadata, or summary objects
  • For very complex logic, switch to a traditional loop with manual assignment
  • Combine with .items(), zip(), or enumerate() when needed

How Dictionary Comprehensions Work

A dictionary comprehension has the form {key: value for item in iterable if condition}. It builds a new dictionary in one expression, which is ideal for lookups, renaming maps and per-group summaries.

If two items produce the same key, the later one silently overwrites the earlier one. When duplicates are possible, aggregate first or use collections.defaultdict.

Inverting a dictionary with {v: k for k, v in d.items()} only works safely when the values are unique.

Worked Example: Lookups, Renames and Inversion

We build several dictionaries from simple data and observe what happens with duplicate keys.

prices = {"pen": 1.5, "notebook": 3.0, "bag": 25.0}

with_tax = {item: round(p * 1.08, 2) for item, p in prices.items()}
cheap = {item: p for item, p in prices.items() if p < 5}
print(with_tax)
print(cheap)

columns = ["Order ID", "Customer Name", "Amount USD"]
rename = {c: c.lower().replace(" ", "_") for c in columns}
print(rename)

codes = {"N": "North", "S": "South", "X": "North"}
inverted = {v: k for k, v in codes.items()}
print(inverted)

The rename map is ready to pass to df.rename(columns=rename). The inverted dictionary shows the duplicate-key trap: North appears twice as a value, so only the last code, X, survives.

Common Mistakes

  • Overwriting values when keys repeat.
  • Inverting dictionaries with non-unique values.
  • Writing long nested dictionary comprehensions.
  • Building a dict comprehension when dict(zip(...)) is simpler.

Quick Summary

  • {k: v for ...} builds dictionaries.
  • Later duplicate keys win.
  • Great for rename maps and lookups.
  • Invert only when values are unique.

Conclusion

Dictionary comprehensions are a powerful and very Pythonic tool in data science. In 2026, they are commonly used to create column mappings, feature dictionaries, summary statistics, and configuration objects in a single readable line. Use them liberally for simple transformations, but fall back to traditional loops when the logic becomes complex or requires multiple steps.

Next steps:

  • Look for places in your code where you manually build dictionaries with loops and replace them with dictionary comprehensions where the logic is straightforward

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