popitem(): removes and returns the last inserted key-value pair from a dictionary as a tuple

popitem(), takes no argument ( inputs ) .

Returns : the key value pair of recently added to dictionary as a tuple.

The original dictionary is changed after removal of key value pair.
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'>

Example: Handling Empty Dictionary

my_dict = {}
try:
    my_dict.popitem()
except KeyError as e:
    print(f"Error: {e}")
Output:
Error: 'popitem(): dictionary is empty'

Example: Removing Items Until 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.

Example: LIFO Operation

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)

Example 5: Handling Nested Dictionaries

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

All dictionary methods
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer