码迷,mamicode.com
首页 > 其他好文 > 详细

4. 字典

时间:2015-06-14 09:24:43      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

创建字典
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}

 

字典应用实例

技术分享

运行测试:

[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>





4. 字典

标签:

原文地址:http://www.cnblogs.com/51runsky/p/4574586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!