EN
Python - remove dictionary items
0
points
In this article, we would like to show you how to remove dictionary items in Python.
Quick solution:
my_dict = {
"id": 1,
"name": "Tom",
"age": 25
}
my_dict.pop("age")
1. Practical example using pop()
method
In this example, we use pop()
method that removes the item with specified key name.
my_dict = {
"id": 1,
"name": "Tom",
"age": 25
}
my_dict.pop("age")
print(my_dict.items()) # [('id', 1), ('name', 'Tom')]
Output:
dict_items([('id', 1), ('name', 'Tom')])
2. Using popitem()
method
In this example, we use popitem()
method that removes the last inserted item.
my_dict = {
"id": 1,
"name": "Tom",
"age": 25
}
my_dict.popitem()
print(my_dict.items()) # [('id', 1), ('name', 'Tom')]
Output:
dict_items([('id', 1), ('name', 'Tom')])
Note:
In versions earlier than Python 3.7 the
popitem()
method removes random item instead.
3. Using del
keyword
In this example, we use del
keyword that removes item with the specified key name.
my_dict = {
"id": 1,
"name": "Tom",
"age": 25
}
del my_dict["age"]
print(my_dict.items()) # [('id', 1), ('name', 'Tom')]
Output:
dict_items([('id', 1), ('name', 'Tom')])
4. Clear the dictionary
In this example, we use clear()
method to empty the dictionary.
my_dict = {
"id": 1,
"name": "Tom",
"age": 25
}
my_dict.clear()
print(my_dict.items()) # []
Output:
dict_items([])