4. 字典
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()创建字典
字典应用实例
运行测试:
[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>