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:
xxxxxxxxxx
1
my_dict = {
2
"id": 1,
3
"name": "Tom",
4
"age": 25
5
}
6
7
my_dict.pop("age")
In this example, we use pop()
method that removes the item with specified key name.
xxxxxxxxxx
1
my_dict = {
2
"id": 1,
3
"name": "Tom",
4
"age": 25
5
}
6
7
my_dict.pop("age")
8
9
print(my_dict.items()) # [('id', 1), ('name', 'Tom')]
Output:
xxxxxxxxxx
1
dict_items([('id', 1), ('name', 'Tom')])
In this example, we use popitem()
method that removes the last inserted item.
xxxxxxxxxx
1
my_dict = {
2
"id": 1,
3
"name": "Tom",
4
"age": 25
5
}
6
7
my_dict.popitem()
8
9
print(my_dict.items()) # [('id', 1), ('name', 'Tom')]
Output:
xxxxxxxxxx
1
dict_items([('id', 1), ('name', 'Tom')])
Note:
In versions earlier than Python 3.7 the
popitem()
method removes random item instead.
In this example, we use del
keyword that removes item with the specified key name.
xxxxxxxxxx
1
my_dict = {
2
"id": 1,
3
"name": "Tom",
4
"age": 25
5
}
6
7
del my_dict["age"]
8
9
print(my_dict.items()) # [('id', 1), ('name', 'Tom')]
Output:
xxxxxxxxxx
1
dict_items([('id', 1), ('name', 'Tom')])
In this example, we use clear()
method to empty the dictionary.
xxxxxxxxxx
1
my_dict = {
2
"id": 1,
3
"name": "Tom",
4
"age": 25
5
}
6
7
my_dict.clear()
8
9
print(my_dict.items()) # []
Output:
xxxxxxxxxx
1
dict_items([])