Add Keys
To add a new key-value pair to a dictionary in Python, you can use the following methods:
1. Direct assignment:
Python
my_dict = {"name": "Alice", "age": 30}
my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
2. update() method:
Python
my_dict = {"name": "Alice", "age": 30}
my_dict.update({"city": "New York"})
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
3. setdefault() method: This method is useful when you want to add a key-value pair only if the key doesn't already exist:
Python
my_dict = {"name": "Alice", "age": 30}
city = my_dict.setdefault("city", "Unknown")
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'Unknown'}
print(city) # Output: 'Unknown'
Key points:
- Keys must be unique within a dictionary.
- You can add new key-value pairs at any time.
- The update() method is useful for merging multiple dictionaries.
- The setdefault() method is helpful for avoiding redundant checks.