A dictionary is a mutable collection of key-value pairs. A single key-value pair represents a single dictionary item.
Items can be added or removed from a dictionary.
We use the pop()
method to remove an item from the dictionary.
The pop()
method removes an item whose key is given as argument. It returns the value associated with the removed item.
Consider the following example
In the above example, we used pop()
to remove the item whose key is 'Madrid'
, the value of this item is returned which is 'Spain'.
When the given key does not exist in the dictionary, the pop()
method raises a KeyError
exception.
The pop()
method allows a second optional argument to specify a default value that will be returned if the key does not exist instead of raising the KeyError
.
pop()
with default
To set a default value that will be returned instead of raising the KeyError
exception, you can pass a second argument to pop()
. The syntax is as shown below:
pop(key, default = None)
If the default
value is given, it will be returned if the key does not exist in the dictionary.
In the above example, we passed a string, 'Key does not exist'
as the default. You can pass any type of object as default not just strings.
Remove dict item using del
The del
statement provides an alternative approach of deleting dictionary items. This approach is suitable if we do not need the value of the deleted item. Its syntax is as shown below:
del dict[key]
The del
statement simply deletes the item whose key is given, it does not return the value of the item.
Similarly, a KeyError
exception is raised if the key dos not exist.
Conclusion
- The
pop()
method removes an item whose key is given as argument. pop()
raises aKeyError
if the given key does not exist in the dictionary.- A default value can be passed to
pop()
so that it will be returned in case the key does not exist. - Alternatively, the
del
statement can be used to remove an item from the dictionary. It is suitable if we do not need the value of the deleted item.