Python 简明教程
Python - Remove Dictionary Items
Remove Dictionary Items
在 Python 中删除字典项是指从现有字典中删除键值对。字典是可变数据结构,它们包含键及其相关值的对。每个键充当一个唯一的标识符,映射到字典内特定值。
Removing dictionary items in Python refers to deleting key-value pairs from an existing dictionary. Dictionaries are mutable data structures that hold pairs of keys and their associated values. Each key acts as a unique identifier, mapping to a specific value within the dictionary.
从字典中删除项使您可以消除字典中不必要或不需要的数据,从而减小其规模并修改其内容。
Removing items from a dictionary allows you to eliminate unnecessary or unwanted data from the dictionary, thereby reducing its size and modifying its content.
我们可使用多种方式在 Python 中移除字典项,例如 −
We can remove dictionary items in Python using various ways such as −
-
using the del keyword
-
using the pop() method
-
using the popitem() method
-
using the clear() method
-
using dictionary comprehension
Remove Dictionary Items Using del Keyword
Python 中的 del 关键字用于删除对象。在字典的情况下,它用于从 dictionary 中删除某一项或一系列项,其依据是指定键。
The del keyword in Python is used to delete objects. In the context of dictionaries, it is used to remove an item or a slice of items from the dictionary, based on the specified key(s).
我们可以通过指定要删除项的键来使用 del 关键字移除字典项。这会从字典中删除与指定键相关联的键值对。
We can remove dictionary items using the del keyword by specifying the key of the item we want to remove. This will delete the key-value pair associated with the specified key from the dictionary.
Example 1
在以下示例中,我们创建一个名为 numbers 的字典,其中包含整数键和它们对应的字符串值。然后,使用 del 关键字删除键为 '20' 的项 −
In the following example, we are creating a dictionary named numbers with integer keys and their corresponding string values. Then, delete the item with the key '20' using the del keyword −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
print ("numbers dictionary before delete operation: \n", numbers)
del numbers[20]
print ("numbers dictionary before delete operation: \n", numbers)
它将生成如下输出:
It will produce the following output −
numbers dictionary before delete operation:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
numbers dictionary before delete operation:
{10: 'Ten', 30: 'Thirty', 40: 'Forty'}
Example 2
当 del 关键字用于字典对象时,它会从内存中删除该字典 −
The del keyword, when used with a dictionary object, removes the dictionary from memory −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
print ("numbers dictionary before delete operation: \n", numbers)
del numbers
print ("numbers dictionary before delete operation: \n", numbers)
以下是所获得的输出 −
Following is the output obtained −
numbers dictionary before delete operation:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
Traceback (most recent call last):
File "C:\Users\mlath\examples\main.py", line 5, in <module>
print ("numbers dictionary before delete operation: \n", numbers)
^^^^^^^
NameError: name 'numbers' is not defined
Remove Dictionary Items Using pop() Method
Python 中的 pop() 方法用于从字典中移除指定键并返回相应的值。如果未找到指定键,它可以选择返回默认值而不是引发 KeyError。
The pop() method in Python is used to remove a specified key from a dictionary and return the corresponding value. If the specified key is not found, it can optionally return a default value instead of raising a KeyError.
我们可以通过指定要删除项的键来使用 pop() 方法来移除字典项。此方法将返回与指定键相关联的值,并将键值对从字典中移除。
We can remove dictionary items using the pop() method by specifying the key of the item we want to remove. This method will return the value associated with the specified key and remove the key-value pair from the dictionary.
Example
在此示例中,我们使用 pop() 方法从 'numbers' 字典中删除键为 '20'(将其值存储在 val 中)的项。然后我们检索更新后的字典和弹出的值 −
In this example, we are using the pop() method to remove the item with the key '20' (storing its value in val) from the 'numbers' dictionary. We then retrieve the updated dictionary and the popped value −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
print ("numbers dictionary before pop operation: \n", numbers)
val = numbers.pop(20)
print ("nubvers dictionary after pop operation: \n", numbers)
print ("Value popped: ", val)
以下是上面代码的输出: -
Following is the output of the above code −
numbers dictionary before pop operation:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
nubvers dictionary after pop operation:
{10: 'Ten', 30: 'Thirty', 40: 'Forty'}
Value popped: Twenty
Remove Dictionary Items Using popitem() Method
Python 中的 popitem() 方法用于从字典中移除并返回最后的键值对。
The popitem() method in Python is used to remove and return the last key-value pair from a dictionary.
我们可以通过对字典调用 popitem() 方法来移除字典项,此方法会移除并返回添加到字典中的最后一个键值对。
We can remove dictionary items using the popitem() method by calling the method on the dictionary, which removes and returns the last key-value pair added to the dictionary.
Example
在以下示例中,我们使用 popitem() 方法从 'numbers' 字典中移除任意项(将键值对存储在 val 中),并且检索更新后的字典以及弹出的键值对 −
In the example below, we use the popitem() method to remove an arbitrary item from the dictionary 'numbers' (storing both its key-value pair in val), and retrieve the updated dictionary along with the popped key-value pair −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
print ("numbers dictionary before pop operation: \n", numbers)
val = numbers.popitem()
print ("numbers dictionary after pop operation: \n", numbers)
print ("Value popped: ", val)
以上代码的输出如下所示 −
Output of the above code is as shown below −
numbers dictionary before pop operation:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
numbers dictionary after pop operation:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty'}
Value popped: (40, 'Forty')
Remove Dictionary Items Using clear() Method
Python 中的 clear() method 用于从字典中移除所有项。这会有效地清空字典,使其长度为 0。
The clear() method in Python is used to remove all items from a dictionary. It effectively empties the dictionary, leaving it with a length of 0.
我们可以通过对字典对象调用 clear() 方法来移除字典项。此方法从字典中移除所有键值对,使其有效地变为空。
We can remove dictionary items using the clear() method by calling it on the dictionary object. This method removes all key-value pairs from the dictionary, effectively making it empty.
Example
在以下示例中,我们使用 clear() 方法从 'numbers' 字典中移除所有项 −
In the following example, we are using the clear() method to remove all items from the dictionary 'numbers' −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
print ("numbers dictionary before clear method: \n", numbers)
numbers.clear()
print ("numbers dictionary after clear method: \n", numbers)
我们得到了如下输出 −
We get the output as shown below −
numbers dictionary before clear method:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
numbers dictionary after clear method:
{}
Remove Dictionary Items Using Dictionary Comprehension
字典解析是一种在 Python 中创建字典的简洁方式。它遵循与列表解析相同的语法,但生成的是字典而不是列表。利用字典解析,您可以遍历可迭代对象(如列表、元组或其他字典),针对每项应用表达式,并根据该表达式的结果构造键值对。
Dictionary comprehension is a concise way to create dictionaries in Python. It follows the same syntax as list comprehension but generates dictionaries instead of lists. With dictionary comprehension, you can iterate over iterable objects (such as lists, tuples, or other dictionaries), apply an expression to each item, and construct key-value pairs based on the result of that expression.
如果您需要根据特定条件从字典中移除项,您通常会使用 del、pop() 或 popitem() 等其他方法。这些方法使您可以明确指定要从字典中移除哪项。
If you need to remove items from a dictionary based on certain conditions, you would typically use other methods like del, pop(), or popitem(). These methods allow you to explicitly specify which items to remove from the dictionary.
Example
在此示例中,我们根据要移除的预定义键列表,从 'student_info' 字典中移除 'age' 和 'major' 项 −
In this example, we remove items 'age' and 'major' from the 'student_info' dictionary based on a predefined list of keys to remove −
# Creating a dictionary
student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Removing items based on conditions
keys_to_remove = ["age", "major"]
for key in keys_to_remove:
student_info.pop(key, None)
print(student_info)
获得的输出如下所示 −
The output obtained is as shown below −
{'name': 'Alice'}