Python基础教程代码与注释P55 4.1 字典的使用 4.2.1 dict函数 4.2.3 字典的格式化字符串 4.2.3 字典的格式化字符串

# -*- 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>")



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值