第七节课:字典

字典是无序的,它不能通过偏移量来索引,只能通过键来存取.
字典= {'key':value} key:类似我们现实的钥匙,而value则是锁。一个钥匙开一个锁.
特点:
内部没有顺序,通过键来读取内容,可嵌套,方便我们组织多种数据结构,并且原地修改里面的内容,属于可变类型.
组成字典的键必须是不可变的数据类型,比如 数字、字符串,元组等. 列表是可变对象不能作为键.

键是字符串:info = {'a':1,'b':2}
键是数字: info2 = {1:'a',2:'b'}
键是元组: cinfo = {(1,2,3):'aaa',(3,4):'bbb'}
键是元组:dinfo = {(2,[2,3]):'a',(3,4):'b'} 且元组中含可变对象,会报错

1. 创建字典: {} dict()
ainfo = {'name':'lilei', 'age':20}
binfo = dict(name = 'liming', age = 22)


2. 添加内容:a['xx'] = 'xx'

binfo['phone'] = 'iphone5s' 不存在键,添加


3. 修改内容:a['xx'] = 'yy'
binfo['phone'] = 'htc' 已经存在键,则修改。

update 参数是一个字典类型,他会覆盖相同键的值
ainfo.update({'city':'beojing','phone':'nokia'})
ainfo.update({'city':'beojing','phone':'htc'})

4. 删除 del clear pop
del ainfo['city']
del ainfo 删除 ainfo 对数据的引用,ainfo不存在了
binfo.clear() 删除字段的全部元素,为空字段, binfo才是存在的


pop方法:返回键值对应的值,并且删除原字典中的键和值
>>> a = dict(name = 'liming', age = 22)
>>> a.pop('name')
'liming'


对比 列表的pop方法:通过下标索引,反馈下标对应的值,并从列表中删除下标对应的值

>>> binfo = []
>>> binfo.append('a')
>>> binfo.append('b')
>>> binfo.append('c')
>>> binfo
['a', 'b', 'c']
>>> binfo.pop(0)
'a'
>>> binfo
['b', 'c']


相同点是删除反馈值并删除对应的值,不同点是字段的pop方法在异常的时候可以返回你想要的值

>>> a = [1,2,3]
>>> a.pop(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> b = {'a':1,'b':2}
>>> b.pop('c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> b.pop('c','meiyouzhi')
'meiyouzhi'
>>> b
{'a': 1, 'b': 2}


5. in 和 has_key() 成员关系操作
5.1 phone in info
5.2 info.has_key('phone')

>>> a = {'a':1,'b':2}
>>> a
{'a': 1, 'b': 2}
>>> 'a' in a
True
>>> 'c' in a
False
>>> a.has_key('aa')
False
>>> a.has_key('a')
True

6. keys(): 返回的是列表, 里面包含了字段的 所有键
values():返回的是列表, 里面包含了字段的 所有值
items: 生成一个字段的容器 :[()]

>>> ainfo = {'name':'lilei', 'age':20}
>>> ainfo.keys()
['age', 'name']
>>> ainfo.values()
[20, 'lilei']
>>> ainfo.items()
[('age', 20), ('name', 'lilei')]
>>> type(ainfo.items())
<type 'list'>
>>> type(ainfo.items()[0])
<type 'tuple'>
>>> ainfo.items()[1]
('name', 'lilei')



7. get 取字段的值

直接根据键取值,无法取到的时候会报错

>>> ainfo = {'name':'lilei', 'age':20}
>>> ainfo['name']
'lilei'
>>> ainfo['names']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'names'


用get方法取值,如果键不存在,返回一个NoneType类型的值,可以设定返回的默认值.

>>> ainfo
{'age': 20, 'name': 'lilei'}
>>> ainfo.get('name')
'lilei'
>>> ainfo.get(name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
>>> ainfo.get('names')
>>> type(ainfo.get('names'))
<type 'NoneType'>
>>> ainfo.get('names','none')
'none'
原文地址:https://www.cnblogs.com/huiming/p/5528924.html