python字典如何增加删除键值?
相关推荐:《python视频》

Python字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何Python数据类型。
1、新建Python字典
立即学习“Python免费学习笔记(深入)”;
>>> dict1={} #建立一个空字典>>> type(dict1) < type 'dict'>
2、增加Python字典元素:两种方法
>>> dict1['a']=1 #第一种
>>> dict1
{'a': 1}#第二种:setdefault方法
>>> dict1.setdefault('b',2)
2
>>> dict1 {'a': 1, 'b': 2}3、删除Python字典
#删除指定键-值对
>>> dict1
{'a': 1, 'b': 2}
>>> del dict1['a'] #也可以用pop方法,dict1.pop('a')
>>> dict1
{'b': 2}
#清空字典
>>> dict1.clear()
>>> dict1 #字典变为空了
{}
#删除字典对象
>>> del dict1
>>> dict1 Traceback (most recent call last):
File "< interactive input>", line 1, in < module>
NameError: name 'dict1' is not defined以上就是python字典增加删除键值的方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号