- Using
del
:- Removes a key-value pair by specifying the key.
pythonmy_dict = {'a': 1, 'b': 2}
del my_dict['a']
- Using
pop()
:- Removes a key and returns its value.
pythonmy_dict = {'a': 1, 'b': 2}
value = my_dict.pop('a') # Returns 1
- Using
popitem()
:- Removes and returns the last inserted key-value pair (in Python 3.7+).
pythonmy_dict = {'a': 1, 'b': 2}
key, value = my_dict.popitem() # Removes and returns ('b', 2)
- Using
clear()
:- Removes all key-value pairs in the dictionary.
pythonmy_dict = {'a': 1, 'b': 2}
my_dict.clear() # Clears the entire dictionary
- Note: Using
del
orpop()
on a non-existent key will raise aKeyError
. Usedict.get()
orin
to check existence first.
4o mini