python学习手册四
字典的使用
创建:字典由多个键与其对应的值构成,也可以将键与其的值称为项,每个键与值之间用‘:’隔开,每个项之间用‘,’隔开,整个字典用一对大括号括起来,空字典由两个大括号括起来,列:
phonebook={'alice':'234','bench':'456','cedil':'443'}
其中键是唯一的,值不是唯一的,也就是说一个键可以对应多个值
1.dict函数:可以用dict函数,通过其他映射(比如其他字典)或者(键,值)这样的序列对建立字典
>>> items=[('name','gumby'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'gumby'}
>>> d['age']
42
>>> phonebook['alice']'234'
2.基本的字典操作
Len(字典名字):返回d中项(键-值)对的数量
>>> a={'one':1,'two':2,'three':3}
>>> len(a)
3
K in d:检查字典d中是否含有键位k的项,查找的是键,不是值,表达式v in l:在列表中查找的是值,而不是索引
注意:键可以为任何不可变的类型,列:
>>> x=[]
>>> x[41]='foobar'
Traceback (most recent call last):
File "<pyshell#24>", line 1,in <module>
x[41]='foobar'
IndexError: list assignment index out of range
>>> x={}
>>> x[41]='foobar'
>>> x
{41: 'foobar'}
在列表中,将字符串关联到空列表的41号位置是不可能的,因为这个位置不存在,必须要使用[none]*42初始化X才可以,但是在字典中就是可以添加的
>>> y=[None]*42
>>> y[41]='abc'
>>> y
[None, None, None, None, None, None, None, None, None, None, None,None, None, None, None, None, None, None, None, None, None, None, None, None,None, None, None, None, None, None, None, None, None, None, None, None, None,None, None, None, None, 'abc']
这样就可以了
字典示列:使用人名作为键的字典,每个人使用另一个字典表示,其键‘phone’和‘addr’分别表示他们的电话号码和地址
people={'xiaoming':{'phone':'123','addr':'beijing'},
'laowang':{'phone':'234','addr':'sahnghai'},
'Jeson':{'phone':'345','addr':'shenzheng'}}
#针对电话号码和地址进项详细的描述:
labels={'phone':'phonenumber','addr':'address'}
#输入姓名后进行查找:
name=raw_input('Name:')
#查找电话号码还是地址,使用正确的键:
print "number (p) or address(a)"
request=raw_input('request:')
if request=='p':key='phone'
if request=='a':key='addr'
#如果名字是字典中的有效键才打印信息:
if name in people:print "%s's %s is%s." %(name,labels[key],people[name][key])
输出:
阅读更多Name:xiaoming
number (p) or address(a)
request:p
xiaoming's phone number is 123.
- python学习手册笔记--第9章--元组文件及其他
- 【Python学习】python学习手册--第三十一章 类的高级主题
- python学习手册4 知识记录。
- python学习手册总结1
- python学习手册(3)
- 【Python学习】python学习手册--第十四章 迭代器和解析 第一部分
- 《Python 学习手册4th》 第十章 Python语句简介
- 【Python学习】python学习手册--第二十五章 OOP:宏伟蓝图
- python学习手册笔记--第10章--语句简介--第11章--复制_表达式_打印
- [python学习手册]if语句
- Python学习手册――unicode和字节字符串
- 【Python学习】python学习手册--第四章 Python对象类型
- Python3 学习手册(一) 基本数据类型
- 我们编程吧 之 python 学习手册0.75
- 【Python学习】python学习手册--第二十三章 模块包
- 《Python 学习手册4th》 第八章 列表与字典
- python学习手册 第6章
- python学习手册笔记--第14.20章--迭代器和解析
- python3.3官方手册学习(第一部分)
- 【Python学习】python学习手册--第十二章 if语句与语法规则