In this tutorial, we’ll learn how to use Python dictionary popitem() method using proper Python code examples with step by step explanation.
Outline
- Introduction: Python Dictionary popitem() Method
- Syntax of popitem() Method
- Example 1: popitem() Method applied on a Dictionary
- Example 2: Removing Latest Inserted Item from Dictionary
- Example 3: popitem() Method Return Value
- Example 4: Using popitem() on an empty Dictionary
- Conclusion
Introduction: Python Dictionary popitem() Method
This method is used to remove/delete the last or latest item(key, value) inserted in Python dictionary.
Syntax of popitem() Method
dictionaryName.popitem()
- This method does not take any arguments.
- It removes and returns the last/latest item inserted in the specified Python dictionary.
Example 1: popitem() Method applied on a Dictionary
items={'a':'Zeeshan','b':'white','c':6} print(items.popitem()) print(items)
Output
('c', 6) {'a': 'Zeeshan', 'b': 'white'}
As you can see here that the last item(key, value) is removed from the dictionary.
Example 2: Removing Latest Inserted Item from Dictionary
items={'a':'Zeeshan','b':'white','c':6} items['g']=22.4 print(items.popitem()) print(items)
Output
('g', 22.4) // latest inserted items {'a': 'Zeeshan', 'b': 'white', 'c': 6}
The latest inserted item(key, value) is removed using Python dictionary popitem method.
Example 3: popitem() Method Return Value
itemsDictionary={'a':'Zeeshan','b':'white','c':6} returnedValue=itemsDictionary.popitem() print(returnedValue)
Output
('c', 6)
The deleted/removed value is returned by Python dictionary popitem() method.
Example 4: Using popitem() on an empty Dictionary
itemsDictionary={} print( itemsDictionary.popitem() )
Output
KeyError: 'popitem(): dictionary is empty'
This method will raise a key error if its applied on an empty dictionary.
Conclusion
To conclude this tutorial, hope you now have a complete and in-depth practical knowledge of how to use Python dictionary popitem() method. I’ll be very glad to have your valuable feedback on this post. Thank you for reading it.
You may like to read:
How To Use Python Dictionary Items Method – Easy Python Guide