刪除 Python 中的字典元素


你可以刪除單獨的字典元素,也可以清空字典的全部內容。你還可以用一個操作刪除整個字典。

要明確刪除整個字典,只需使用 del 語句。

示例

下面是一個簡單的示例 −

 線上演示

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

輸出

會生成以下結果,注意,會引發異常,因為在 del dict 之後,字典將不復存在 −

dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

注意 − del() 方法將在下一部分討論。

更新於: 2020 年 1 月 28 日

638 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告