Python 字典 clear() 方法



Python 字典 clear() 方法用於一次性刪除字典中所有元素(鍵值對)。因此它會返回一個空字典。

當字典中元素過多時,逐一刪除每個元素需要很長時間。相反,可以使用 clear() 方法一次性刪除所有元素。

語法

以下是Python 字典 clear() 方法的語法:

dict.clear()

引數

此方法不接受任何引數。

返回值

此方法不返回任何值。

示例

以下示例演示了 Python 字典 clear() 方法的用法。這裡我們建立了一個字典 'Animal'。然後使用 clear() 方法刪除字典 'Animal' 中的所有元素。

Animal = {"Name":"Lion","Kingdom":"Animalia","Class":"Mammalia","Order":"Carnivora"}
print("Elements of the dictionary before removing elements are: ", str(Animal))
res = Animal.clear()
print("Elements of the dictionary after removing elements are: ", res)

執行上述程式時,會產生以下結果:

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

示例

在下面的程式碼中,建立了一個字典 'dict'。然後使用 clear() 方法刪除字典 'dict' 中的所有元素。這裡,我們獲取刪除元素前後字典的長度。

dict = {'Name': 'Zara', 'Age': 7};
print ("Start Len : %d" %  len(dict))
dict.clear()
print ("End Len : %d" %  len(dict))

以下是上述程式碼的輸出:

Start Len : 2
End Len : 0

示例

下面的程式碼顯示了 clear() 方法和將 {} 賦值給現有字典之間的區別。透過將 {} 賦值給字典,建立一個新的空字典並將其賦值給給定的引用。而透過在字典引用上呼叫 clear() 方法,則會刪除實際字典的元素。因此,所有引用該字典的引用都將變為空。

dict_1 = {"Animal": "Lion", "Order": "Carnivora"}
dict_2 = dict_1
# Using clear() method
dict_1.clear()
print('The first dictionary dict_1 after removing items using clear() method: ', dict_1)
print('The second dictionary dict_2 after removing items using clear() method: ', dict_2)

dict_1 = {"Player": "Sachin", "Sports": "Cricket"}
dict_2 = dict_1
# Assigning {}
dict_1 = {}
print('The first dictionary dict_1 after removing items by assigning {}:', dict_1)
print('The second dictionary dict_2 after removing items by assigning {}: ', dict_2)

上述程式碼的輸出如下:

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'}
python_dictionary.htm
廣告