Easy Tutorial
❮ Python String Splitlines Ref Math Pow ❯

Python3 Dictionary popitem() Method

Python3 Dictionary


Description

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

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

Syntax

Syntax for the popitem() method:

popitem()

Parameters

Return Value

Returns the last inserted key-value pair (in key, value format) according to the LIFO (Last In First Out) order, which is the last key-value pair.

Note: Before Python3.7, the popitem() method removed and returned an arbitrary key-value pair from the dictionary.

Example

The following example demonstrates the use of the popitem() method:

#!/usr/bin/python3

site = {'name': 'tutorialpro.org', 'alexa': 10000, 'url': 'www.tutorialpro.org'}

# The last inserted ('url', 'www.tutorialpro.org') will be removed
result = site.popitem()

print('Return Value = ', result)
print('site = ', site)

# Inserting a new element
site['nickname'] = 'tutorialpro'
print('site = ', site)

# Now ('nickname', 'tutorialpro') is the last inserted element
result = site.popitem()

print('Return Value = ', result)
print('site = ', site)

Output:

Return Value =  ('url', 'www.tutorialpro.org')
site =  {'name': 'tutorialpro.org', 'alexa': 10000}
site =  {'name': 'tutorialpro.org', 'alexa': 10000, 'nickname': 'tutorialpro'}
Return Value =  ('nickname', 'tutorialpro')
site =  {'name': 'tutorialpro.org', 'alexa': 10000}

Python3 Dictionary

❮ Python String Splitlines Ref Math Pow ❯