Remove Keys
To remove a key-value pair from a dictionary in Python, you can use the following methods:
1. del statement:
Python
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
del my_dict["age"]
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
2. pop() method:
Python
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
age = my_dict.pop("age")
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
print(age) # Output: 30
The pop() method removes the specified key-value pair and returns the value associated with the key. If the key doesn't exist, it raises a KeyError by default, but you can provide a default value to avoid the exception:
Python
value = my_dict.pop("country", "Unknown")
print(value) # Output: "Unknown"
3. clear() method:
This method removes all key-value pairs from the dictionary:
Python
my_dict.clear()
print(my_dict) # Output: {}
Key points:
- The del statement and pop() method are both effective for removing keys.
- The pop() method returns the removed value.
- The clear() method removes all elements.
- Be careful with the del statement, as it can raise a KeyError if the key doesn't exist.