python学习手册四

来源:互联网 发布:睡眠工作 知乎 编辑:程序博客网 时间:2024/05/19 19:29

字典的使用

创建:字典由多个键与其对应的值构成,也可以将键与其的值称为项,每个键与值之间用‘:’隔开,每个项之间用‘,’隔开,整个字典用一对大括号括起来,空字典由两个大括号括起来,列:

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.

0 0