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
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)get("kiwi", 0) returns 0 because there is no "kiwi" key. stock["kiwi"] would crash with a KeyError.del removes the "pear" key and its value.apple 4.fruit changes from 'apple' to 'plum'. count changes from 4 to 7.plum 7.for fruit, count in stock.items().in to check for a key before relying on itAnswer: {"a": 2}. Keys are unique; the value is replaced.
Answer: d.get("x"). get returns None (or your default).
← Tuples and Unpacking · Sets: Unique Items →