文中代码

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.cnblogs.com/hahaa/p/17050590.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!