Python Dictionary pop() Method

Python 字典Python Dictionary


Description

The Python dictionary pop() method deletes the value corresponding to the given key in the dictionary, and the return value is the deleted value.

Syntax

The syntax of the pop() method is:

pop(key[,default])

Parameters

  • key- The key to be deleted
  • default- The value to return when the key does not exist

Return Value

Returns the deleted value:

  • Ifkeyexists - deletes the corresponding element in the dictionary
  • Ifkeydoes not exist - returns the default value specified by default
  • Ifkeydoes not exist and no default value default is specified - triggers anKeyErrorexception

Example

The following example demonstrates how to use the pop() method:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

site= {'name': 'Example', 'alexa': 10000, 'url': 'www.example.com'}

element = site.pop('name')

print('Deleted element:')
print(element)
print('Dictionary:')
print(site)

Output result:

删除的元素为:
Example
字典为:
{'url': 'www.example.com', 'alexa': 10000}

If the key to be deleted does not exist, an exception will be triggered:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

site= {'name': 'Example', 'alexa': 10000, 'url': 'www.example.com'}

element = site.pop('nickname')

print('Deleted element:')
print(element)
print('Dictionary:')
print(site)

Output result:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    element = site.pop('nickname')
KeyError: 'nickname'

You can set a default value to avoid the exception:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

site= {'name': 'Example', 'alexa': 10000, 'url': 'www.example.com'}

element = site.pop('nickname', 'non-existent key')

print('Deleted element:')
print(element)
print('Dictionary:')
print(site)

Output result:

 
删除的元素为:
不存在的 key
字典为:
{'url': 'www.example.com', 'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}

Python 字典Python Dictionary

Other Extensions