In this Python tutorial, you will learn what pop() method of dictionary dict class does, its syntax, and how to use this method to remove an item from the dictionary, with example programs.

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

The syntax of dict.pop() is

</>
Copy
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.

Examples (3)

1. Delete an entry from dictionary by a 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

</>
Copy
myDictionary = {'a': 58, 'b': 61, 'c': 39}
value = myDictionary.pop('b')
print(value)
print(myDictionary)

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.

2. Return a default value if the key (we are trying to delete) is not present in dictionary

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

</>
Copy
myDictionary = {'a': 58, 'b': 61, 'c': 39}
value = myDictionary.pop('k', 0)
print(value)
print(myDictionary)

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.

3. Delete an entry from dictionary, where given key is not present

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

</>
Copy
myDictionary = {'a': 58, 'b': 61, 'c': 39}
value = myDictionary.pop('k')
print(value)
print(myDictionary)

Program Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    value = myDictionary.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().