# -*- coding: cp936 -*-
#P55 4.1 字典的使用
#假定有一个列表如下
names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']#人名列表
#对应的分机电话号码如下
numbers = ['2341', '9102', '3158', '0142', '5551'] #分机电话号码,应表示为数字字符串
#index 从列表中找出某个值第一个匹配项的索引位置
print numbers[names.index('Cecil')] #找出某个人的号码
#若用字典
phonebook = {
'Alice': '2341',
'Beth': '9102',
'Cecil':'3158',
'Dee-Dee':'0142',
'Earl': '5551'
}
print "Cecil's phone number is " + phonebook['Cecil'] + "."
print "Cecil's phone number is %(Cecil)s." % phonebook #字典的格式化字符串
raw_input("Press <enter>")
# -*- coding: cp936 -*-
#P56 4.2 创建和使用字典
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} #'键:值'对
#4.2.1 dict函数 通过其它映射(如字典)或者(键,值)对的序列建立字典
items = [('name','Gumby'), ('age', 42)]
d = dict(items)
print d
print d['name']
#dict函数通过关键字参数来创建字典
d = dict(name='Gumby', age=42)
print d
#4.2.2 基本字典操作
x = [] #列表
#x[42] = 'Foobar' #试图将字符串'Foobar''关联到一个空列表的42号位置上,而位置不存在。
x = {} #字典
x[42] = 'Foobar'
print x
print '\n'
#codelist4-1 字典示例
# 一个简单的数据库
# 字典使用人名作为键。每个人用另一个字典来表示,其键‘phone'和'addr'分别表示他们的电话号码和地址。
people = {
'Alice':{
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth':{
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil':{
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
print people
# 针对电话号码和地址使用的描述性标签,会在打印输出的时候用到
labels = {
'phone': 'phone number',
'addr': 'address'
}
name = raw_input('Name: ')
# 查找电话号码还是地址?
request = raw_input('Phone number (p) or address (a)?')
# 使用正确的键:
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])
#4.2.3 字典的格式化字符串
phonebook = {'Beth': '9102','Alice': '2341', 'Cecil': '3258'}
print "Cecil's phone number is %(Cecil)s." % phonebook # %(Cecil)s %(键)s
template = '''<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</boad>'''
data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}
print template % data
raw_input("Press <enter>")
Python基础教程代码与注释P55 4.1 字典的使用 4.2.1 dict函数 4.2.3 字典的格式化字符串 4.2.3 字典的格式化字符串
最新推荐文章于 2023-12-14 00:48:46 发布