Add, Update and Delete Dictionary Items in Python
Add a New Key or Change a Value
To add an item to a dictionary, assign a value to a new key: ages["Lucky"] = 22. The very same line changes the value when the key already exists.
Think of it like a whiteboard of names and scores: writing a new name adds a line, and writing on an existing name rubs out the old score and puts in the new one.
ages = {"Sunny": 25, "Rocky": 30}
ages["Lucky"] = 22
print(ages)
ages["Sunny"] = 26
print(ages){'Sunny': 25, 'Rocky': 30, 'Lucky': 22}
{'Sunny': 26, 'Rocky': 30, 'Lucky': 22}The rules
d[key] = valuewith a new key adds a pair at the end.d[key] = valuewith a key that's already there replaces its value. The key keeps its place.- A dictionary is changed in place, like a list with
append()in chapter 9. No new dictionary is made.
Add up with +=
+= from chapter 5 works on a value too. Here, 5 more apples arrive at the shop:
stock = {"apple": 10, "mango": 4}
stock["apple"] += 5
print(stock){'apple': 15, 'mango': 4}Avoid: += on a key that isn't there
+= first reads the old value. If there is no old value, Python stops:
stock = {"apple": 10}
stock["kiwi"] += 5
print(stock)KeyError: 'kiwi'
To add a brand-new key, use =, not +=: stock["kiwi"] = 5. Or use get() with a default from the last topic, which works either way: stock["kiwi"] = stock.get("kiwi", 0) + 5.
Common beginner doubt: "How do I rename a key?" There's no rename. Add the new key with the old value, then delete the old key. You'll learn deleting two lessons from now.
d[key] = valueadds the key if it's new and changes its value if it's already there.