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

Python Dictionary pop() Method

Python Dictionary pop() Method

Python Dictionary Python Dictionary


Description

The Python Dictionary pop() method removes the value corresponding to the given key in the dictionary and returns the removed value.

Syntax

Syntax of the pop() method:


pop(key[,default])

Parameters

Return Value

Returns the removed value:

Example

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

Example

#!/usr/bin/python

-- coding: UTF-8 --

site

=

{

'name'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

element

=

site

.

pop

(

'name'

)

print

(

'The removed element is:'

)

print

(

element

)

print

(

'The dictionary is:'

)

print

(

site

)

The output is:

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

Deleting a key that does not exist raises an exception:

Example

#!/usr/bin/python

-- coding: UTF-8 --

site

=

{

'name'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

element

=

site

.

pop

(

'nickname'

)

print

(

'The removed element is:'

)

print

(

element

)

print

(

'The dictionary is:'

)

print

(

site

)

The output is:


Traceback (most recent call last):
  File "test.py", line 6, in 
    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'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

element

=

site

.

pop

(

'nickname'

,

'Nonexistent key'

)

print

(

'The removed element is:'

)

print

(

element

)

print

(

'The dictionary is:'

)

print

(

site

)

The output is:

 
The deleted elements are:
不存在的 key
Dictionary is:
{'url': 'www.runoob.com', 'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}

Python Dictionary Python Dictionary