runtime
36 / 250
lesson 36 Dictionaries & Sets · beginner

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.

You'll be able to
  • Write a dictionary literal and read a value with d[key]
  • Explain that in checks the keys, not the values
  • Guard a lookup with in instead of letting a missing key raise KeyError
The idea

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.

example-1.py · A customer record
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)
example-2.py · A key that isn't there
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.

example-3.py · Shipping fee by channel
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 in to 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.
Review
  • A dictionary maps keys to values: {"web": 0, "phone": 3.5}. Read a value with d[key].
  • in checks keys. A missing key raises KeyError, so test with in when 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.

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Make a dictionary and look a value up — Dictionaries & Sets · Runtime