Adding Items to a Dictionary
You can add new items to a dictionary by assigning a value to a new key.
Adding a New Key-Value Pair
Example: Adding an Item
# Adding a new item to a dictionary
person = {"name": "Praveen", "age": 24}
person["city"] = "Hyderabad"
print("Person Dictionary:", person)
Person Dictionary: {'name': 'Praveen', 'age': 24, 'city': 'Hyderabad'}
Using update()
Method
Example: Adding Multiple Items
# Adding multiple items using update()
person.update({"email": "praveen@example.com", "phone": "1234567890"})
print("Person after update:", person)
Person after update: {'name': 'Praveen', 'age': 24, 'city': 'Hyderabad', 'email': 'praveen@example.com', 'phone': '1234567890'}
Explanation: Adding a new key-value pair is straightforward. If the key does not exist, it will be added; if it exists, the value will be updated.