python学习(1)-字典 (Dictionary)
字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何python数据类型。
1、新建字典
>>> dict1={} #建立一个空字典
>>> type(dict1)
<type ‘dict’>
2、增加字典元素:两种方法
>>> dict1['a']=1 #第一种
>>> dict1
{‘a’: 1}
#第二种:setdefault方法
>>> dict1.setdefault(‘b’,2)
2
>>> dict1
{‘a’: 1, ‘b’: 2}
3、删除字典
#删除指定键-值对
>>> 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
继续阅读 »
近期评论