Python dictionary clear() 方法用于一次删除字典中存在的所有元素(键值对)。因此,它会检索一个空字典。
当字典中的元素太多时,将每个元素逐个删除需要很长时间。相反,请使用 clear() 方法一次删除所有元素。
语法
以下是 Python dictionary clear() 方法的语法 -
参数
此方法不接受任何参数。
返回值
此方法不返回任何值。
例以下示例显示了 Python 字典 clear() 方法的用法。在这里,我们正在创建一个字典 'Animal'。然后使用 clear() 方法删除字典 'Animal' 中存在的所有元素。
当我们运行上述程序时,它会产生以下结果——
Elements of the dictionary before removing elements are: {'Name': 'Lion', 'Kingdom': 'Animalia', 'Class': 'Mammalia', 'Order': 'Carnivora'}
Elements of the dictionary after removing elements are: None
Elements of the dictionary after removing elements are: None
例
在下面的代码中,创建了一个字典 'dict'。然后使用 clear() 方法删除字典 'dict' 中存在的所有元素。在这里,我们检索字典在删除其元素之前和之后的长度。
以下是上述代码的输出 -
Start Len : 2
End Len : 0
End Len : 0
例
下面的代码显示了 clear() 方法和将 {} 分配给现有字典之间的区别。通过将 {} 分配给字典,创建一个新的空字典并将其分配给给定的引用。而通过在字典引用上调用 clear() 方法,实际字典的元素被删除。因此,引用字典的所有引用都变为空。
上述代码的输出如下 -
The first dictionary dict_1 after removing items using clear() method: {}
The second dictionary dict_2 after removing items using clear() method: {}
The first dictionary dict_1 after removing items by assigning {}: {}
The second dictionary dict_2 after removing items by assigning {}: {'Player': 'Sachin', 'Sports': 'Cricket'}
The second dictionary dict_2 after removing items using clear() method: {}
The first dictionary dict_1 after removing items by assigning {}: {}
The second dictionary dict_2 after removing items by assigning {}: {'Player': 'Sachin', 'Sports': 'Cricket'}