Skip to content

Python Update Dictionaries

Syntax

You can update dictionaries in Python by modifying existing keys, adding new key-value pairs, or using the update() method.

# Updating an existing key's value
person = {"name": "Alice", "age": 25}
person["age"] = 26 # Update age to 26
# Adding a new key-value pair
person["city"] = "New York"
# Using the update() method
person.update({"country": "USA", "age": 27}) # Updates or adds multiple key-value pairs

Example

# Updating a dictionary of product details
product = {
"name": "Laptop",
"price": 999.99,
"stock": 50
}
# Updating the price
product["price"] = 899.99
print(f"Updated price: ${product['price']}")
# Adding a new key-value pair for discount
product["discount"] = "10%"
print(f"Product details after adding discount: {product}")
# Using update() to modify multiple fields
product.update({"price": 850.00, "stock": 45})
print(f"Final product details: {product}")