Make a dictionary and look a value up
A dictionary stores values under keys you choose: customer["city"] instead of customer[2]. Looking up a key that isn't there raises KeyError, so check with in first.
- Write a dictionary literal and read a value with
d[key] - Explain that
inchecks the keys, not the values - Guard a lookup with
ininstead of letting a missing key raise KeyError
A customer record could be a list, ["C00164", "Isaac", "New York"], but then you have to remember that position 2 means the city. A dictionary stores each value under a key you choose, so the code says what it means: customer["city"].
Write a dictionary with curly braces and key: value pairs, separated by commas. Read a value by putting its key in square brackets. Keys are usually text, and each key appears once.
Run each example to see what it prints. Running examples doesn't count toward progress.
customer = {"customer_id": "C00164", "first_name": "Isaac", "city": "New York", "segment": "consumer"}
print(customer["first_name"], customer["city"])
print(len(customer))
print("city" in customer, "New York" in customer, "email" in customer)customer = {"customer_id": "C00164", "first_name": "Isaac", "city": "New York"}
print(customer["city"])
print(customer["email"])A dictionary is also a lookup table: give it a key, get the matching value in one step, however many pairs it holds. Shipping fees per sales channel are a typical example. Test with in before you look a key up when the key comes from data you don't control.
fees = {"web": 0, "app": 0, "marketplace": 5.99, "phone": 3.5}
channel = "marketplace"
subtotal = 6.49
if channel in fees:
print(f"Shipping {fees[channel]:.2f}, total {subtotal + fees[channel]:.2f}")
else:
print("Unknown channel:", channel)
twice = {"web": 0, "web": 4.99}
print(twice)When to use it: for a record whose fields have names, and for any lookup from a code to its meaning or price. Mistakes to avoid:
- Expecting
into search the values. - Looking up a key that may be missing without checking first.
- Mixing up the key's spelling or capitals:
"Web"and"web"are different keys.
- A dictionary maps keys to values:
{"web": 0, "phone": 3.5}. Read a value withd[key]. inchecks keys. A missing key raises KeyError, so test withinwhen the key comes from data.- A key appears once, so writing it again replaces its value.
- Next: add, change and remove pairs as data changes.