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
prices["date"] = 5.00 # add a new key
prices["apple"] = 1.50 # update existing
del prices["cherry"] # remove
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
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), ...])
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.
price_list = {
"SKU-001": 19.99,
"SKU-002": 29.99,
"SKU-003": 9.99,
}
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}")
d[key]..get(key, default) to avoid KeyError on missing keys..items() when you need both key and value.Given a sentence, build a dict where each key is a word and each value is how many times it appears.