python字典怎么删除键
python中的字典是另一种可变容器模型,且可存储任意类型对象。键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。
Python删除字典元素的4种方法
1.Python字典的clear()方法(删除字典内所有元素)
#!/usr/bin/python
#-*-coding:UTF-8-*-
dict={'name':'我的博客地址','alexa':10000,'url':}
dict.clear();#清空词典所有条目
2.Python字典的pop()方法(删除字典给定键key所对应的值,返回值为被删除的值)
#!/usr/bin/python
#-*-coding:UTF-8-*-
site={'name':'我的博客地址','alexa':10000,'url':}
pop_obj=site.pop('name')#删除要删除的键值对,如{'name':'我的博客地址'}这个键值对
printpop_obj#输出:我的博客地址
3.Python字典的popitem()方法(随机返回并删除字典中的一对键和值)
#!/usr/bin/python
#-*-coding:UTF-8-*-
site={'name':'我的博客地址','alexa':10000,'url':'}
pop_obj=site.popitem()#随机返回并删除一个键值对
printpop_obj#输出结果可能是{'url','http://blog.csdn.net/uuihoo/'}
4.del全局方法(能删单一的元素也能清空字典,清空只需一项操作)
#!/usr/bin/python
#-*-coding:UTF-8-*-
site={'name':'我的博客地址','alexa':10000,'url':}
delsite['name']#删除键是'name'的条目
delsite#清空字典所有条目
以上内容为大家介绍了python字典怎么删除键,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






