HomeCourseModule 06 › Dictionaries — key-value lookups

Dictionaries — key-value lookups

Module 06 · Data Structures9 min readBeginner

What you'll learn

  • Create and access dictionaries
  • Use .get() to avoid KeyError
  • Iterate keys, values, and items

What's a dict?

A dictionary maps keys to values. It's a lookup table.

prices = {
    "apple":  1.20,
    "banana": 0.50,
    "cherry": 3.00,
}

prices["apple"]    # 1.20
prices["banana"]   # 0.50

Adding and updating

prices["date"] = 5.00        # add a new key
prices["apple"] = 1.50       # update existing
del prices["cherry"]         # remove

The .get() escape hatch

Accessing a missing key crashes:

prices["mango"]   # KeyError!

.get() returns None (or a default) instead:

prices.get("mango")          # None
prices.get("mango", 0)       # 0  — supply a default

Iterating

for fruit in prices:
    print(fruit)             # just keys

for fruit, price in prices.items():
    print(f"{fruit}: ${price}")

prices.keys()    # dict_keys(['apple', 'banana', ...])
prices.values()  # dict_values([1.20, 0.50, ...])
prices.items()   # dict_items([('apple', 1.20), ...])

The "row as dict" pattern — this one's important

Real-world data often looks like one dict per row:

customers = [
    {"id": 1, "name": "Alice",  "city": "NYC",     "ltv": 1200},
    {"id": 2, "name": "Bob",    "city": "Chicago", "ltv":  800},
    {"id": 3, "name": "Carol",  "city": "NYC",     "ltv": 2200},
]

# Find all NYC customers
nyc = [c for c in customers if c["city"] == "NYC"]
# Total NYC LTV
total = sum(c["ltv"] for c in customers if c["city"] == "NYC")

Pandas DataFrames are basically a faster version of this same structure. Internalise the pattern and DataFrames will feel natural.

Walkthrough: build a quick price lookup

Define the lookup

price_list = {
    "SKU-001": 19.99,
    "SKU-002": 29.99,
    "SKU-003":  9.99,
}

Cost a basket

basket = [("SKU-001", 2), ("SKU-002", 1), ("SKU-099", 4)]   # last one isn't in the list

total = 0
for sku, qty in basket:
    price = price_list.get(sku)
    if price is None:
        print(f"Unknown SKU: {sku}")
        continue
    total += price * qty

print(f"Total: ${total:.2f}")

Key takeaways

  • Dicts map keys to values: d[key].
  • Use .get(key, default) to avoid KeyError on missing keys.
  • Iterate with .items() when you need both key and value.
  • Lists of dicts are the precursor to a DataFrame.

Word counter

Given a sentence, build a dict where each key is a word and each value is how many times it appears.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.