Removing Items from a Dictionary
You can remove items from a dictionary using methods like pop()
, popitem()
, del
, and clear()
.
Using pop()
Method
Example: Removing an Item by Key
# Removing an item using pop()
person = {'name': 'Williams', 'age': 29, 'city': 'Bangalore'}
age = person.pop('age')
print("Removed Age:", age)
print("Person Dictionary:", person)
Removed Age: 29
Person Dictionary: {'name': 'Williams', 'city': 'Bangalore'}
Using popitem()
Method
Example: Removing the Last Inserted Item
# Removing the last item using popitem()
item = person.popitem()
print("Removed Item:", item)
print("Person Dictionary:", person)
Note: In Python 3.7 and later, popitem()
removes the last inserted item.
Removed Item: ('city', 'Bangalore')
Person Dictionary: {'name': 'Williams'}
Using del
Keyword
Example: Deleting an Item
# Deleting an item using del
del person['name']
print("Person Dictionary:", person)
Person Dictionary: {}
Using clear()
Method
Example: Clearing the Dictionary
# Clearing all items in a dictionary
person = {'name': 'Karthick AG', 'age': 30}
person.clear()
print("Person Dictionary after clear:", person)
Person Dictionary after clear: {}
Explanation: There are multiple ways to remove items from a dictionary. The pop()
method removes the item with the specified key and returns its value. The popitem()
method removes the last inserted key-value pair. The del
keyword can delete a specific item or the entire dictionary.