文中代碼
smart_girl = {"name":"yuan wai", "age": 25,"address":"Beijing"}
第一種方式:pop()方法
注意:找不到對應的key,pop方法會拋出例外KeyError
smart_girl.pop("name") #回傳值是value # Python學習交流裙 708525271
第二種方式:popitem()方法
注意:popitem()方法會隨機洗掉一個Entry,然后回傳洗掉的Entry(每個Entry是key與value組成的一個Tuple物件)
注意:字典為空,呼叫此方法,會報出KeyError
smart_girl.popitem() #回傳被洗掉的Entry
第三種方式:pop()方法,增加容錯
smart_girl.pop("name", "容錯方案") #找不到key,回傳指定的默認值
第四種方式:使用del
注意:找不到對應的key,會拋出例外
del smart_girl["name"]
第五種方式:使用clear()
smart_girl.clear() #清空全部元素
第六種方式:使用del清空字典物件
del smart_girl #干掉字典物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/543011.html
標籤:其他
上一篇:5 組合資料型別
下一篇:7 錯誤及例外處理
