Dictionaries: Keys and Values

Store values under keys: add, update, look up safely with get, delete, and loop over pairs with items().

Python · beginner · 7 min · 11 steps · free

What you'll learn

dicts.py

stock = {"apple": 5, "pear": 2}
stock["plum"] = 7               # add a new key
stock["apple"] = stock["apple"] - 1
kiwis = stock.get("kiwi", 0)    # a default instead of an error
del stock["pear"]
for fruit, count in stock.items():
    print(fruit, count)
print(len(stock), kiwis, "plum" in stock)

Step by step

  1. A dictionary: each key ("apple") maps to a value (5).
  2. Assigning to a new key adds it.
  3. Assigning to an existing key replaces its value: 5 - 1 = 4.
  4. get("kiwi", 0) returns 0 because there is no "kiwi" key. stock["kiwi"] would crash with a KeyError.
  5. del removes the "pear" key and its value.
  6. items() gives each (key, value) pair in turn, in the order they were added.
  7. It prints apple 4.
  8. fruit changes from 'apple' to 'plum'. count changes from 4 to 7.
  9. It prints plum 7.
  10. Python moves to the next item of the loop: for fruit, count in stock.items().
  11. Two keys remain, apple: 4 and plum: 7. Dictionaries are the go-to tool for looking things up by name.

Common mistakes

Best practices

Key takeaways

Check yourself

d = {"a": 1}; d["a"] = 2. What is d?

Answer: {"a": 2}. Keys are unique; the value is replaced.

Which never raises an error for a missing key?

Answer: d.get("x"). get returns None (or your default).

·

More in Collections