Python - Dictionary Methods Part 2: Adding and Updating Data
These methods allow adding new entries or modifying existing key-value pairs.
Methods and Examples
update() Method Updates the dictionary with another dictionary or key-value pairs.
my_dict.update({"country": "USA", "age": 26})
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}
Explanation: The update() method modifies existing keys or adds new ones.
Direct Assignment Add or update a specific key-value pair.
my_dict["profession"] = "Engineer"
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA', 'profession': 'Engineer'}
Explanation: Direct assignment is simple for individual key-value additions.
Setting Default with setdefault() Sets a default value if the key does not exist.
my_dict.setdefault("hobby", "Reading")
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA', 'profession': 'Engineer', 'hobby': 'Reading'}
Explanation: setdefault() avoids overwriting existing keys while ensuring a default value.