Python - Add Dictionary Items
Add Items to a Dictionary
In Python, you can add new items (key-value pairs) to a dictionary in two ways:
- Using square brackets
[]
- Using the
update()
method
Example 1: Add Item Using Square Brackets
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "Red"
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red'}
Explanation: Since "color"
was not a key in the dictionary, it was added with the value "Red"
.
Example 2: Add Item Using update()
Method
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"engine": "V8"})
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red', 'engine': 'V8'}
Explanation: The update()
method added the "engine"
key with its value to the dictionary.
Example 3: Add Multiple Items at Once
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({
"doors": 2,
"fuel": "Petrol"
})
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red', 'engine': 'V8', 'doors': 2, 'fuel': 'Petrol'}
Explanation: The update()
method can add multiple key-value pairs in a single call by passing another dictionary.
Example 4: Add Item Conditionally
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "owner" not in car:
car["owner"] = "Alice"
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red', 'engine': 'V8', 'doors': 2, 'fuel': 'Petrol', 'owner': 'Alice'}
Explanation: We added "owner"
only if it didn't already exist in the dictionary.
When to Use Which Method?
Feature | Square Brackets [] | update() Method |
---|---|---|
Add single item | ✅ | ✅ |
Add multiple items | ❌ | ✅ (pass a dict) |
Overwrite existing | ✅ | ✅ |
Conditional add | Manually check with in | Manually check with in |
Conclusion
Adding items to a dictionary in Python is simple and flexible. Use square brackets for quick additions and update()
for batch inserts or cleaner code.