Dictionaries are mutable, which means that we can modify them after their creation.
x = {"oranges": 1, "apples": 4}
x["oranges"] = 3
print(x["oranges"])
This would print 3
because the value corresponding to the key "oranges" was updated with the value 3
.
This update could equally be implemented as
x.update({"oranges": 3})
Let's look at a slightly more complicated example:
stock = { ("Warehouse A", "Product X"): 3, ("Warehouse A", "Product Y"): 0, ("Warehouse B", "Product X"): 9, ("Warehouse B", "Product Y"): 1, ("Warehouse C", "Product X"): 3, ("Warehouse C", "Product Y"): 10, } print(stock[("Warehouse A", "Product X")])
The dictionary above stores the quantity of stock available for products X and Y at warehouses A, B, C.
The dictionary uses tuples as keys, where the first element of the tuple represents the warehouse and the second represents the product. The values represent the quantity in stock.
Note: We are using tuples and not lists because dictionary keys must be immutable.
Now let's say we would like to update the quantity in stock for multiple products simultaneously. We could do:
stock.update( { ("Warehouse A", "Product X"): 1, ("Warehouse C", "Product Y"): 5, } ) print(stock[("Warehouse A", "Product X")]) print(stock[("Warehouse C", "Product Y")])
which would print
1
5
To remove a key-value pair from the dictionary, use the pop
method:
stock.pop(("Warehouse A", "Product X"))
To access the keys and values of the stock
dictionary, you can use stock.keys()
and stock.values()
. You can also access the keys and values simultaneously using stock.items()
. Later we will see how this can be handy.
Copy the definition of the stock
dicitionary to your answer.
Then perform the following modifications:
(Wareouse A, Product Z)