Python dictionaries (dict) are “mutable” (changeable) objects. This means you can add new key-value pairs or change values associated with existing keys even after the dictionary is created.
An interesting point is that Python uses the exact same syntax for both “adding new elements” and “updating existing elements.”
This article explains the behavior of adding and updating data in dictionaries.
Basic Syntax
To write to a dictionary, use the following syntax:
dict_variable[key] = value
When this is executed, the Python interpreter processes it as follows:
- If the key does not exist: Adds it as a new key-value pair.
- If the key already exists: Overwrites (updates) the value corresponding to that key with the new value.
1. Adding New Elements
If you assign a value to a key that does not exist in the dictionary, that pair is added. Let’s use fruit stock management data as an example.
# Initial stock data
fruit_stock = {
"apple": 50,
"orange": 30
}
print(f"Before: {fruit_stock}")
# Add new item "banana" (stock 20)
# Since the key "banana" does not exist yet, it is added as new.
fruit_stock["banana"] = 20
print(f"After: {fruit_stock}")
Output:
Before: {'apple': 50, 'orange': 30}
After: {'apple': 50, 'orange': 30, 'banana': 20}
The new key "banana" and its value 20 have been stored in the dictionary.
2. Updating Existing Elements (Overwriting)
If you assign a value to a key that already exists, the original value is replaced by the new value.
# Current stock data
# {'apple': 50, 'orange': 30, 'banana': 20}
# Change stock of "apple" from 50 to 45
# Since the key "apple" already exists, this becomes an update.
fruit_stock["apple"] = 45
print(f"Updated: {fruit_stock}")
Output:
Updated: {'apple': 45, 'orange': 30, 'banana': 20}
The value of "apple" changed from 50 to 45.
Application: Updating by Calculation
It is also common to perform a calculation based on the current value and update with the result. In this case, you can use compound assignment operators (+=, -=, etc.).
# 10 oranges were sold (decrease stock)
fruit_stock["orange"] -= 10 # Same as: fruit_stock["orange"] = fruit_stock["orange"] - 10
print(f"Calc Update: {fruit_stock}")
Output:
Calc Update: {'apple': 45, 'orange': 20, 'banana': 20}
Summary
- Dictionary element manipulation is done with the unified syntax
dict[key] = value. - If the specified key is missing, it is added; if present, it is updated (overwritten).
- Be careful about the existence of keys to avoid accidental overwrites (check with the
inoperator if necessary).
