Python Fundamentals ยท Collections

Dictionaries: Keys and Values

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

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.