Python Fundamentals ยท Collections
Store values under keys: add, update, look up safely with get, delete, and loop over pairs with items().
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().