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 valueperson = {"name": "Alice", "age": 25}person["age"] = 26 # Update age to 26
# Adding a new key-value pairperson["city"] = "New York"
# Using the update() methodperson.update({"country": "USA", "age": 27}) # Updates or adds multiple key-value pairsExample
# Updating a dictionary of product detailsproduct = { "name": "Laptop", "price": 999.99, "stock": 50}
# Updating the priceproduct["price"] = 899.99print(f"Updated price: ${product['price']}")
# Adding a new key-value pair for discountproduct["discount"] = "10%"print(f"Product details after adding discount: {product}")
# Using update() to modify multiple fieldsproduct.update({"price": 850.00, "stock": 45})print(f"Final product details: {product}")