logo
Python Data Structures - Interview Questions and Answers
What is the difference between del, pop(), and popitem() in dictionaries?

In Python, del, pop(), and popitem() are used to remove elements from a dictionary, but they work differently. Here’s a breakdown of their differences:


1. del – Removes a Key-Value Pair by Key
  • Deletes a specific key and its value from the dictionary.
  • Raises a KeyError if the key doesn’t exist.
  • Can delete the entire dictionary if used without a key.
Example :
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Delete a specific key
del my_dict["age"]
print(my_dict)  # Output: {'name': 'Alice', 'city': 'New York'}

# Delete the entire dictionary
del my_dict
# print(my_dict)  # Raises NameError because the dictionary is deleted.

* Use when you want to remove a specific key or delete the whole dictionary.


2. pop() – Removes and Returns a Value by Key
  • Removes a specific key and returns its value.
  • Raises a KeyError if the key doesn’t exist, unless a default value is provided.
Example :
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Remove 'age' and return its value
removed_value = my_dict.pop("age")
print(removed_value)  # Output: 25
print(my_dict)  # Output: {'name': 'Alice', 'city': 'New York'}

# Using pop() with a default value to avoid KeyError
removed_value = my_dict.pop("country", "Not Found")
print(removed_value)  # Output: Not Found

* Use when you want to remove a key and retrieve its value.


3. popitem() – Removes and Returns the Last Inserted Key-Value Pair
  • Removes and returns the last inserted (key, value) pair as a tuple.
  • Raises a KeyError if the dictionary is empty.
Example :
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Remove and return the last item
removed_item = my_dict.popitem()
print(removed_item)  # Output: ('city', 'New York')
print(my_dict)  # Output: {'name': 'Alice', 'age': 25}

* Use when you want to remove the most recently added key-value pair (useful for stacks or LIFO operations).


Comparison Table :
Method Removes Returns Value? Raises Error if Key Missing? Deletes Entire Dictionary?
del Specific key or entire dict No Yes Yes
pop() Specific key Yes Yes (unless default is given) No
popitem() Last inserted key-value pair Yes (as a tuple) Yes No