Python Dictionary popitem()
In the python dictionary, the popitem() method returns and removes the last pair of the given dictionary.
Python Dictionary popitem()
The syntax of popitem() is:
1
2
dictionary.popitem()
popitem() Parameters
The popitem() does not take any parameters as arguments.
Let see some examples of the popitem() method in dictionaries.
Example 1: How to use the popitem() method in python dictionaries?
1
2
3
4
5
6
7
8
9
10
11
cars = {"BMW" : 1,"TOYOTA" : 2,"TATA" : 3}
print("Removed items is:",cars.popitem())
print("New Dictionary is :",cars)
print("Removed items is:",cars.popitem())
print("New Dictionary is :",cars)
print("Removed items is:",cars.popitem())
print("New Dictionary is :",cars)
Output:
1
2
3
4
5
6
7
Removed items is: ('TATA', 3)
New Dictionary is : {'BMW': 1, 'TOYOTA': 2}
Removed items is: ('TOYOTA', 2)
New Dictionary is : {'BMW': 1}
Removed items is: ('BMW', 1)
New Dictionary is : {}
Example 2: using popitem() with only one element in dictionaries.
1
2
3
4
5
6
7
8
cars = {"BMW" : 1}
print("Removed items is:",cars.popitem())
print("New Dictionary is :",cars)
print("Removed items is:",cars.popitem())
print("New Dictionary is :",cars)
Output 1:
1
2
3
4
5
6
7
Removed items is: ('BMW', 1)
New Dictionary is : {}
Traceback (most recent call last):
File "", line 6, in <module>
print("Removed items is:",cars.popitem())
KeyError: 'popitem(): dictionary is empty
As you can see it throws a KeyError exception when there is no item present in the dictionary.
Rules of popitem()
- The popitem() method works on LIFO order (Last in, First out).
- It will remove the last key-value pair from the dictionary.
- Throw KeyError when no item is left in the dictionary.
This post is licensed under CC BY 4.0 by the author.