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

Python3 Dictionary popitem() Method

Python3 Dictionary popitem() Method

Python3 Dictionaries Python3 Dictionary


Description

The Python dictionary popitem() method returns and removes the last pair of key and value from the dictionary.

If the dictionary is already empty when this method is called, a KeyError exception is raised.

Syntax

popitem() method syntax:



popitem()

Parameters

Return Value

Returns the last inserted key/value pair (in key, value form), following the LIFO (Last In First Out) rule, i.e. the last key/value pair.

**Note:** before Python 3.7, popitem() removed and returned an arbitrary key/value pair from the dictionary.

Example

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

Example

#!/usr/bin/python3

site

=

{

'name'

:

'Runoob Tutorial'

,

'alexa'

:

10000

,

'url'

:

'www.runoob.com'

}

('url': 'www.runoob.com') was inserted last, so it is removed

result

=

site

.

popitem

(

)

print

(

'Return value = '

,

result

)

print

(

'site = '

,

site

)

Insert a new element

site

[

'nickname'

]

=

'Runoob'

print

(

'site = '

,

site

)

Now ('nickname', 'Runoob') is the last inserted element

result

=

site

.

popitem

(

)

print

(

'Return value = '

,

result

)

print

(

'site = '

,

site

)

The output is:



返回值 =  ('url', 'www.runoob.com')

site =  {'name': 'Runoob Tutorial', 'alexa': 10000}

site =  {'name': 'Runoob Tutorial', 'alexa': 10000, 'nickname': 'Runoob'}

返回值 =  ('nickname', 'Runoob')

site =  {'name': 'Runoob Tutorial', 'alexa': 10000}


Python3 Dictionaries Python3 Dictionary