學習如何在Python中利用字典刪除元素

Python 的 Dict(字典)是一種非常有用的資料結構,它可以讓我們快速地存取資料。在使用字典時,有時候我們需要刪除其中的元素,Python 提供了幾種方法來讓我們快速地刪除字典中的元素。

使用 del 關鍵字刪除元素

del 關鍵字可以讓我們快速地刪除字典中的元素,例如:

d = {'a':1, 'b':2, 'c':3}
del d['b']
print(d)

執行結果:

{'a': 1, 'c': 3}

使用 pop() 方法刪除元素

pop() 方法也可以讓我們快速地刪除字典中的元素,它會回傳被刪除的元素,例如:

d = {'a':1, 'b':2, 'c':3}
x = d.pop('b')
print(x)
print(d)

執行結果:

2
{'a': 1, 'c': 3}

使用 popitem() 方法刪除元素

popitem() 方法也可以讓我們快速地刪除字典中的元素,它會回傳一個元組,元組中包含被刪除的鍵和值,例如:

d = {'a':1, 'b':2, 'c':3}
x = d.popitem()
print(x)
print(d)

執行結果:

('c', 3)
{'a': 1, 'b': 2}

使用 clear() 方法刪除元素

clear() 方法可以讓我們快速地清空字典中的所有元素,例如:

d = {'a':1, 'b':2, 'c':3}
d.clear()
print(d)

執行結果:

{}

總結:Python 的 Dict(字典)提供了 del、pop()、popitem() 和 clear() 方法來讓我們快速地刪除字典中的元素。

發佈留言