๐ ๏ธ How to Change, Update, or Add Items in a Python Dictionary | TechTown.in
Dictionaries in Python are mutable, which means you can modify, add, or overwrite values anytime โ even after the dictionary is created.
In this guide, weโll explore all the ways to update and manage dictionary items in Python โ using direct assignment, .update() method, and real-life examples.
๐ฆ Example Dictionary
person = {
"name": "Tanmay",
"age": 22,
"city": "Jaipur"
}
๐ 1. Changing the Value of an Existing Key
Just use the key name and assign a new value:
person["age"] = 23
print(person)
# {'name': 'Tanmay', 'age': 23, 'city': 'Jaipur'}
โ Quick and direct.
โ 2. Adding a New Key-Value Pair
Use the same syntax โ if the key doesn’t exist, Python will add it.
person["email"] = "tanmay@example.com"
print(person)
๐ฏ Output:
{'name': 'Tanmay', 'age': 23, 'city': 'Jaipur', 'email': 'tanmay@example.com'}
๐ 3. Use update() Method (Add or Modify)
person.update({"age": 24, "gender": "Male"})
print(person)
๐ This method can update existing keys and add new ones at the same time.
๐ง Real-Life Example: Updating Product Info
product = {
"id": 101,
"name": "Laptop",
"price": 60000
}
product["price"] = 57999 # price drop
product.update({"stock": 12})
Useful for eCommerce apps, admin panels, and APIs.
๐งช Bonus: Nested Dictionary Update
student = {
"name": "Aditi",
"marks": {"math": 80, "science": 85}
}
student["marks"]["math"] = 90
โ You can even update values inside nested dictionaries!
๐ Summary โ Ways to Update a Dictionary in Python
| Task | Method | Use Case |
|---|---|---|
| Change existing value | dict[key] = new_value | Quick updates |
| Add new key-value pair | dict[new_key] = value | Extend dictionary |
| Modify multiple values | dict.update({...}) | Batch updates |
| Nested dictionary update | dict[key][subkey] = value | Complex data structures |
๐ Final Thoughts
Dictionaries in Python are extremely flexible. Whether you’re handling user profiles, updating product data, or modifying API responses โ knowing how to change and add values is essential.
Use direct assignment for simple changes, and .update() when you want to add or modify multiple items at once.
๐ Learn more about Python dictionaries at TechTown.in