Python3 Dictionary pop() Method
Description
The Python dictionary pop() method removes the value corresponding to the key in the dictionary and returns the removed value. If the key does not exist, it can optionally return a default value (if provided).
Syntax
pop() method syntax:
dict.pop(key, default)
Parameters
key: the key to be removed.default(optional): The default value returned if the key does not exist. If no default value is provided and the key does not exist, anKeyErrorexception is raised.
Return Value
Returns the deleted value:
- If
keythe key exists - removes the corresponding element from the dictionary - If
keythe key does not exist - returns the specified default value default - If
keythe key does not exist and the default value default is not specified - raises anKeyErrorexception.
Example
The following example demonstrates how to use the pop() method:
Example
#!/usr/bin/python3
site= {'name': 'Rookie Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
element = site.pop('name')
print('The deleted element is:', element)
print('The dictionary is:', site)
site= {'name': 'Rookie Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
element = site.pop('name')
print('The deleted element is:', element)
print('The dictionary is:', site)
The output result is:
删除的元素为: Example
字典为: {'alexa': 10000, 'url': 'www.example.com'}
If the key to be deleted does not exist, an exception will be raised:
Example
#!/usr/bin/python3
site= {'name': 'Rookie Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
element = site.pop('nickname')
print('The deleted element is:', element)
print('The dictionary is:', site)
site= {'name': 'Rookie Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
element = site.pop('nickname')
print('The deleted element is:', element)
print('The dictionary is:', site)
The output result is:
File "/Users/EXAMPLE/example-test/test.py", line 5, in <module>
element = site.pop('nickname')
KeyError: 'nickname'
You can set a default value to avoid the exception:
Example
#!/usr/bin/python3
site= {'name': 'Rookie Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
element = site.pop('nickname', 'Non-existent key')
print('The deleted element is:', element)
print('The dictionary is:', site)
site= {'name': 'Rookie Tutorial', 'alexa': 10000, 'url': 'www.example.com'}
element = site.pop('nickname', 'Non-existent key')
print('The deleted element is:', element)
print('The dictionary is:', site)
The output result is:
删除的元素为: 不存在的 key
字典为: {'name': 'Example', 'alexa': 10000, 'url': 'www.example.com'}
Other Extensions
Python3 Dictionary