4. 字典

创建字典
1. { }
>>> dic={'name':'pmghong','age':'22','gender':'male'}
>>> dic['name']
'pmghong'
 
2. 使用工厂方法dict( )
fdict=dict(['x',1],['y',2])
 
3. 内建方法:fromkeys( ) ,字典中的元素具有相同的值,默认为None
ddict={}.fromkeys(('x','y'),-1)

dict函数

可以用dict 函数,通过其他映射(比如其他字典)或(键,值)这样的序列对建立字典。

>>> items = [('name','gumby'),('age',42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'gumby'}
>>> d['name']
'gumby'

dict函数也可以通过关键字参数来创建字典,如下例所示:

>>> d = dict(name ='gumby', age=42)
>>> d
{'age': 42, 'name': 'gumby'}


结合zip()创建字典

>>> a = ['a','b']
>>> b = [123,789]
>>> dict(zip(a,b))
{'a': 123, 'b': 789}

 

字典应用实例

计算机生成了可选文字: #l/usr/bin/python
people={一
'Alice':{
,phone
"addr
},
,Beth':{
,phone
.addr
#definedist
2341
r00
drive23
.创‘日
},
,何ay
2222
FOO
城目喇
drive93
.愁、
:{
ohone
.addr
8888
Fodf
、声几
drive99
}
labels
}
..,电,贬一一厂
={
,phone':'phonenumber
"addr':'address"
#定义一个打印字典
}
、气
,、
name=raw--input("Name:.)
request=
ifrequest
ifrequest
raw
侧
一一一一
_input(
,p':
,a.:
"phone
nunlber(p)
,phonet
,addr'
Or
%5。
address(a)?")
key
key
ifnamein
else:print
people:print
s%515
,,%(name,labels[key],people[name][key])
‘一IJothisname
u%s
in
people,pleasecheck。”

运行测试:

[root@server3 python]# python dict.py

Name:Alice

phone number(p) or address(a)?p

Alice's phone number is 2341.

[root@server3 python]# python dict.py

Name:Beth

phone number(p) or address(a)?a

Beth's address is Foo drive 93.

 

字典的格式化字符串

>>> phonebook

{'Beth': '9928', 'Alice': '2322', 'Cecil': '1314'}

>>> "Cecil's phone number is %(Cecil)s."  %phonebook

"Cecil's phone number is 1314."

应用:

>>> template = '''<html>                 #字符串模板

... <head><title>%(title)s</title></head>

... <body>

... <h1>%(title)s</h1>

... <p>%(text)s</p>

... </body>'''

>>> data = {'title' : 'My Home Page','text' : 'Welcome to my home page!'}

>>> print template %data                

<html>

<head><title>My Home Page</title></head>

<body>

<h1>My Home Page</h1>

<p>Welcome to my home page!</p>

</body>





posted @ 2015-06-14 09:14  51runsky  阅读(100)  评论(0编辑  收藏  举报