Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Dictionary pop() Method

Python3 Dictionary pop() Method

Python3 Dictionaries Python3 Dictionary


Description

The Python dictionary pop() method removes the value corresponding to a key and returns it. If the key does not exist, it can optionally return a default value (if provided).

Syntax

pop() method syntax:


dict.pop(key, default)

Parameters

Return Value

Returns the removed value:

Example

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

Example

#!/usr/bin/python3

site

=

{

'name'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

element

=

site

.

pop

(

'name'

)

print

(

'The removed element is:'

,

element

)

print

(

'The dictionary is:'

,

site

)

The output is:

删除的元素为: Runoob Tutorial
字典为: {'alexa': 10000, 'url': 'www.runoob.com'}

Deleting a key that does not exist raises an exception:

Example

#!/usr/bin/python3

site

=

{

'name'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

element

=

site

.

pop

(

'nickname'

)

print

(

'The removed element is:'

,

element

)

print

(

'The dictionary is:'

,

site

)

The output is:


File "/Users/RUNOOB/runoob-test/test.py", line 5, in 
    element = site.pop('nickname')
KeyError: 'nickname'

You can set a default value to avoid the exception:

Example

#!/usr/bin/python3

site

=

{

'name'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

element

=

site

.

pop

(

'nickname'

,

'Nonexistent key'

)

print

(

'The removed element is:'

,

element

)

print

(

'The dictionary is:'

,

site

)

The output is:

 
删除的元素为: 不存在的 key
字典为: {'name': 'Runoob Tutorial', 'alexa': 10000, 'url': 'www.runoob.com'}

Python3 Dictionaries Python3 Dictionary