Python for Data Analytics & AutomationLesson 9 of 41
Lesson 9 of 41

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 KeyCategoryUnit CostStock UnitsReorder Alert
BEL_CHOCO_500Tubs₹180.0045Normal
ALM_CRUNCH_500Tubs₹150.0012Restock Triggered
VAN_CONE_100Cones₹25.00120Normal
MANGO_BAR_80Bars₹35.008Critical 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:

Function 1

dict.get(key, default=None)

Definition: Returns the value for key if key is in the dictionary, else default. Avoids raising KeyError exceptions.

Syntax / Code Pattern:
stock_qty = inventory.get("Almond_Crunch", 0)
Parameters Breakdown:
  • key: Hashable object (string, integer, tuple) to look up in hash table.
  • default: Value returned if key does not exist. Defaults to None.
Real-World Example (Dark-Store Stock Lookup):
Problem / Scenario: Safely check inventory for "Blueberry_Cheesecake" without throwing KeyError if unstocked.
Code / Expression: stock = dark_store_inventory.get("Blueberry_Cheesecake", 0)
Result: 0 (fallback integer instead of crash)
Why it works: Since "Blueberry_Cheesecake" was absent from the dictionary, default value 0 is cleanly returned.
Function 2

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.

Syntax / Code Pattern:
customer_orders.setdefault(cust_id, []).append(order_id)
Parameters Breakdown:
  • key: Key to search or insert.
  • default: Value inserted and returned if key is missing.
Real-World Example (Grouping Orders by Customer ID):
Problem / Scenario: Aggregate multiple order IDs under each customer ID list dynamically.
Code / Expression: orders_by_cust.setdefault("CUST_108", []).append("ORD_5021")
Result: {"CUST_108": ["ORD_5021"]}
Why it works: Creates a new empty list on first access, then appends the order without duplicate key lookups.
Function 3

dict.items()

Definition: Returns a dynamic dictionary view object displaying a set-like sequence of (key, value) tuple pairs.

Syntax / Code Pattern:
for category, revenue in store_revenue.items():
Real-World Example (Store Revenue Breakdown):
Problem / Scenario: Iterate over product categories to compute total gross revenue.
Code / Expression: for cat, rev in category_sales.items(): print(f"{cat}: ₹{rev:,}")
Result: Ice Cream: ₹45,000 | Shakes: ₹18,000 | Waffles: ₹12,500
Why it works: Unpacks key-value pairs simultaneously in one readable loop pass.
Function 4

dict.update([other])

Definition: Updates the dictionary with the key/value pairs from other, overwriting existing keys in-place.

Syntax / Code Pattern:
pricing_table.update(seasonal_price_overrides)
Parameters Breakdown:
  • other: Another dictionary or iterable of key/value pairs.
Real-World Example (Promotional Discount Overrides):
Problem / Scenario: Apply summer promotional prices over base pricing dictionary.
Code / Expression: menu_prices.update({"Sundae_Large": 199, "Milkshake_Oreo": 149})
Result: {"Sundae_Large": 199, "Milkshake_Oreo": 149, "Cone_Single": 50}
Why it works: Overwrites existing keys and appends any new promotional items.

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)

ActionWindowsMac
Merge Two Dictionaries (Python 3.9+)dict1 | dict2dict1 | 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.
Dictionaries & Hash Maps: Key-Value | DataCliq