Dictionaries in Python: Key-Value Data Structure for Data Science – Complete Guide 2026
Dictionaries (dict) are one of the most important and frequently used data structures in Python data science. They store data as key-value pairs, allowing lightning-fast lookups, flexible configuration, feature mapping, summary statistics, and JSON-like data handling. In 2026, mastering dictionaries is essential for clean, performant, and readable data science code.
TL;DR — Why Dictionaries Matter
- Key-value storage with O(1) lookup speed
- Keys must be hashable (strings, numbers, tuples)
- Values can be anything (lists, DataFrames, other dicts, etc.)
- Modern Python 3.7+ guarantees insertion order
1. Creating Dictionaries
# Literal syntax
feature_importance = {
"amount": 0.42,
"quantity": 0.31,
"profit": 0.18,
"region": 0.09
}
# From two lists using zip (very common)
features = ["amount", "quantity", "profit"]
scores = [0.42, 0.31, 0.18]
importance_dict = dict(zip(features, scores))
# Dict comprehension
squared = {k: v ** 2 for k, v in feature_importance.items()}
2. 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 name mapping
col_mapping = {
col: col.lower().replace(" ", "_")
for col in df.columns
}
# Example 2: 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)
}
# Example 3: Model configuration as dict
model_config = {
"model_type": "random_forest",
"n_estimators": 200,
"max_depth": 10,
"random_state": 42
}
3. Common Operations
config = {"n_estimators": 200, "max_depth": 10}
# Access
print(config["n_estimators"])
# Safe access
value = config.get("learning_rate", 0.1) # default if missing
# Add / update
config["learning_rate"] = 0.05
config.update({"max_depth": 12})
# Remove
config.pop("max_depth", None) # safe
4. Best Practices in 2026
- Use dict comprehensions for clean transformations
- Prefer
.get()for safe access with defaults - Use
collections.defaultdictwhen you need automatic defaults - Store complex records as dicts or namedtuples/dataclasses
- Keep configuration and hyperparameters as dictionaries
How Dictionaries Work
A dictionary maps unique, hashable keys to values. Like a set, it uses a hash table, so looking up, inserting or deleting a key takes roughly the same time whether the dict holds ten entries or ten million. Since Python 3.7, dictionaries also preserve insertion order, so iterating gives keys back in the order they were first added.
Keys must be hashable (strings, numbers, tuples of those); values can be anything, including lists and other dicts. Assigning to an existing key replaces its value rather than adding a second entry, which is why dictionaries are the natural structure for lookups, counters, caches and configuration.
Worked Example: A Lookup Table Instead of if/elif
region_manager = {
"North": "Ayesha",
"South": "Bilal",
"East": "Chen",
}
orders = [("North", 1250.75), ("West", 300.00), ("East", 2340.00)]
for region, amount in orders:
manager = region_manager.get(region, "Unassigned")
print(f"{region:6} {amount:>9,.2f} -> {manager}")
# Count orders per region with a plain dict
counts = {}
for region, _ in orders:
counts[region] = counts.get(region, 0) + 1
print(counts) # {'North': 1, 'West': 1, 'East': 1}
# Invert a mapping (values must be unique for this to be safe)
manager_region = {name: reg for reg, name in region_manager.items()}
print(manager_region["Chen"]) # East
A dictionary lookup replaces a growing chain of if/elif branches, and adding a new region becomes a data change rather than a code change.
Common Mistakes
- Using
d[key]for keys that may be missing: raisesKeyError; use.get() - Using a list as a key: lists are unhashable; convert to a tuple
- Changing the dict size while looping over it: raises
RuntimeError; loop overlist(d)instead - Inverting a mapping with duplicate values: later keys overwrite earlier ones silently
Quick Summary
- Dicts give fast key-based lookups and keep insertion order
- Use
.get()for safe access and dict comprehensions to build or transform mappings - Replace long
if/elifchains with lookup tables
Conclusion
Dictionaries are the workhorse key-value data structure in Python data science. In 2026, they are used everywhere — from feature mapping and model configuration to summary statistics and JSON-style data handling. Mastering creation, access, modification, and comprehensions will make your code cleaner, faster, and more professional.
Next steps:
- Review your current code and convert any manual key-value handling into clean dictionary usage and comprehensions