创建字典
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}
字典应用实例
运行测试:
[[email protected] python]#
python dict.py
Name:Alice
phone number(p) or
address(a)?p
Alice‘s phone number is
2341.
[[email protected] 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>