Dictionaries & Hash Maps: Key-Value Architecture, Methods & Defaultdict
Overview & Learning Objectives
Dictionaries are Python's implementation of hash maps, mapping immutable keys to arbitrary values with average O(1) time complexity for insertions, lookups, and deletions. Data analysts use dictionaries for indexing dimension tables, JSON API payloads, configuration mappings, and category aggregations.
- Understand hash table architecture, key hashing, and collision resolution.
- Access and mutate keys safely using `.get()`, `.setdefault()`, and `.update()`.
- Iterate efficiently over keys, values, and item tuples using dictionary views.
- Group and aggregate multi-level business metrics using `collections.defaultdict`.
Industry Standard
Standard: Analytics teams at Amazon and Uber mandate using `.get(key, default)` or `defaultdict` over direct subscript lookup `dict[key]` to prevent unhandled KeyError exceptions during ingestion.
Real-World Example: ScoopCraft Ice Cream Inventory Hash Map
ScoopCraft tracks real-time inventory counts and category groupings across retail SKUs.
| SKU Key | Category | Unit Cost | Stock Units | Reorder Alert |
|---|---|---|---|---|
| BEL_CHOCO_500 | Tubs | ₹180.00 | 45 | Normal |
| ALM_CRUNCH_500 | Tubs | ₹150.00 | 12 | Restock Triggered |
| VAN_CONE_100 | Cones | ₹25.00 | 120 | Normal |
| MANGO_BAR_80 | Bars | ₹35.00 | 8 | Critical Shortage |
Functions & Methods Covered in this Chapter
Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/method covered in this chapter:
dict.get(key, default=None)
Definition: Returns the value for key if key is in the dictionary, else default. Avoids raising KeyError exceptions.
stock_qty = inventory.get("Almond_Crunch", 0)
key: Hashable object (string, integer, tuple) to look up in hash table.default: Value returned if key does not exist. Defaults to None.
stock = dark_store_inventory.get("Blueberry_Cheesecake", 0)dict.setdefault(key, default=None)
Definition: If key is in the dictionary, return its value. If not, insert key with a value of default and return default.
customer_orders.setdefault(cust_id, []).append(order_id)
key: Key to search or insert.default: Value inserted and returned if key is missing.
orders_by_cust.setdefault("CUST_108", []).append("ORD_5021")dict.items()
Definition: Returns a dynamic dictionary view object displaying a set-like sequence of (key, value) tuple pairs.
for category, revenue in store_revenue.items():
for cat, rev in category_sales.items(): print(f"{cat}: ₹{rev:,}")dict.update([other])
Definition: Updates the dictionary with the key/value pairs from other, overwriting existing keys in-place.
pricing_table.update(seasonal_price_overrides)
other: Another dictionary or iterable of key/value pairs.
menu_prices.update({"Sundae_Large": 199, "Milkshake_Oreo": 149})Common Mistakes & Limitations
- Iterating through `dict.keys()` just to look up values with `dict[k]`; always use `for k, v in dict.items():`.
- Using mutable objects like lists as dictionary keys, causing `TypeError: unhashable type: 'list'`.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Merge Two Dictionaries (Python 3.9+) | dict1 | dict2 | dict1 | dict2 |
| Quick Inverted Dictionary | {v: k for k, v in d.items()} | {v: k for k, v in d.items()} |
Pro Tips & Modern Best Practices
- Use `collections.Counter` when counting category frequencies or top-N elements.
- Use `collections.ChainMap` to search across multiple dictionaries without memory duplication.