my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.popitem()
print(x)
print(my_dict)
Output is here
('c', 'Three')
{'a': 'One', 'b': 'Two'}
popitem() will remove the latest added element
my_dict={'a':'One','b':'Two','c':'Three'}
my_dict['d']='Four'
x=my_dict.popitem()
print(x)
print(my_dict)
Output
('d', 'Four')
{'a': 'One', 'b': 'Two', 'c': 'Three'}
Data type of removed item is tuple
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.popitem()
print(type(x))
Output
<class 'tuple'>
my_dict = {}
try:
my_dict.popitem()
except KeyError as e:
print(f"Error: {e}")
Output:
Error: 'popitem(): dictionary is empty'
my_dict = {'a': 1, 'b': 2, 'c': 3}
while my_dict:
key, value = my_dict.popitem()
print(f"Removed: {key} -> {value}")
print("Dictionary is now empty.")
Output:
Removed: c -> 3
Removed: b -> 2
Removed: a -> 1
Dictionary is now empty.
stack = {'first': 1, 'second': 2, 'third': 3}
last_in = stack.popitem()
print(f"Last in, first out: {last_in}")
Output:
Last in, first out: ('third', 3)
nested_dict = {'first': {'a': 1}, 'second': {'b': 2}}
outer_key, inner_dict = nested_dict.popitem()
print(f"Removed outer item: {outer_key} -> {inner_dict}")
inner_key, inner_value = inner_dict.popitem()
print(f"Removed inner item: {inner_key} -> {inner_value}")
Output:
Removed outer item: second -> {'b': 2}
Removed inner item: b -> 2
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.