Python Dictionary pop()

Python Dictionary pop(key[, default]) method removes the (key, value) pair and returns the value. But if the key is not present and default is passed as argument, pop() returns the default value.

If default is not passed as argument, pop() method throws KeyError.

Syntax – pop()

The syntax of dict.pop() is

dict.pop(key[, default])

where

key is used to remove the matching key:value pair.

default is returned if no key is found in the dictionary. default is optional.

Example 1 – Python dict.pop(key)

In this example, we will take a dictionary, and delete a key:value pair by passing key as argument to pop() method.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
value = dictionary.pop('b')
print(value)
print(dictionary)
Try Online

Program Output

61
{'a': 58, 'c': 39}

The key ‘b’ we passed as argument to pop() method, is present. Therefore, pop() returned the value, and removed the key:value pair from the dictionary.

Example 2 – Python dict.pop(key, default)

In this example, we will take a dictionary, and delete a key:value pair by passing key as argument to pop() method. But the key we are trying to pop is not present in the dictionary.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
value = dictionary.pop('k', 0)
print(value)
print(dictionary)
Try Online

Program Output

0
{'a': 58, 'b': 61, 'c': 39}

The key ‘k’ we passed as argument to pop() method, is not present in the dictionary. Therefore, pop() returned the default value that we passed as second argument. And the dictionary remains unchanged.

Example 3 – Python dict.pop(key)

In this example, we will try to delete a key:value pair that is not present in the dictionary. Also, we are not passing the default value to the pop() method.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
value = dictionary.pop('k')
print(value)
print(dictionary)
Try Online

Program Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    value = dictionary.pop('k')
KeyError: 'k'

The key ‘k’ we passed as argument to pop() method, is not present. Also, as we have not passed the default value, pop( method raised KeyError.

Conclusion

In this Python Tutorial, we learned about Python Dictionary method dict.pop(). We have gone through the syntax of pop(), and its usage with example programs based on different parameter values.