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

d = {'Berlin': 'Germany', 'Madrid': 'Spain', 'Paris': 'France'}

#remove an item using pop
result = d.pop('Madrid')
print(result)
print(d) #Madrid no longer exists in the dictionary

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.

d = {'Berlin': 'Germany', 'Madrid': 'Spain', 'Paris': 'France'}

#using a non-existent key
d.pop('Manilla')

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.

d = {'Berlin': 'Germany', 'Madrid': 'Spain', 'Paris': 'France'}

#using a non-existent key
result = d.pop('Manilla', 'Key does not exist.')
print(result)
print(d)

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. 

d = {'Berlin': 'Germany', 'Madrid': 'Spain', 'Paris': 'France'}

del d['Paris']

print(d)

Similarly, a KeyError exception is raised if the key dos not exist.

d = {'Berlin': 'Germany', 'Madrid': 'Spain', 'Paris': 'France'}

#using a non-existent key
del d['Manilla']

Conclusion 

  • The pop() method removes an item whose key is given as argument.
  • pop() raises a KeyError 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.