Python Change & Add Dictionary Items
Changing a dictionary item replaces the value stored under a key. Adding a pair stores a value under a new key.
Change a value
Assign a new value to an old key.
prices = {"bread": 2, "milk": 1}
prices["bread"] = 3
print(prices)Add a new pair
Assign a value to a key that is not there yet.
prices = {"bread": 2}
prices["eggs"] = 4
print(prices)Change and add with update()
update() takes several pairs at once. Old keys change and new keys are added.
prices = {"bread": 2, "milk": 1}
prices.update({"milk": 2, "cheese": 5})
print(prices)Add only if absent
setdefault() returns the current value for an old key. It adds the pair only for a new key.
prices = {"bread": 2}
print(prices.setdefault("bread", 9))
print(prices.setdefault("jam", 4))
print(prices)Example
prices = {"bread": 2, "milk": 1, "eggs": 3}
print("Start:", prices)
prices["milk"] = 2
print("Fixed milk:", prices)
prices.update({"cheese": 5, "jam": 4})
print("Final:", prices)Key points
- Assign to an old key to change its value
- Assign to a new key to add a pair
- Use update() to change or add several pairs at once
- Use setdefault() to add a pair only when the key is absent
- update() with an old key changes the value stored under that key.
In this example, prices starts with three pairs. The assignment to milk changes its value from 1 to 2. No new pair is made, because milk is already a key. Then update() adds two new pairs, cheese and jam. The final print shows all five pairs in order.
Note
update() with an old key does not add a second pair.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does prices.setdefault("bread", 9) do when bread is already a key?