第4章 当索引行不通时

代码清单4-1 字典示例

# A simple database

# A dictionary with person names as keys. Each person is represented as
# another dictionary with the keys 'phone' and 'addr' referring to their phone
# number and address, respectively.
people = {

    'Alice': {
        'phone': '2341',
        'addr': 'Foo drive 23'
    },

    'Beth': {
        'phone': '9102',
        'addr': 'Bar street 42'
    },

    'Cecil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }

}

# Descriptive labels for the phone number and address. These will be used
# when printing the output.
labels = {
    'phone': 'phone number',
    'addr': 'address'
}

name = input('Name: ')

# Are we looking for a phone number or an address?
request = input('Phone number (p) or address (a)? ')

# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'

# Only try to print information if the name is a valid key in
# our dictionary:
if name in people: print("{}'s {} is {}.".format(name, labels[key], people[name][key]))

运行结果如下:

Name: Beth
Phone number (p) or address (a)? p
Beth's phone number is 9102.

代码清单4-2 字典方法示例

# A simple database using get()

# Insert database (people) from Listing 4-1 here.
people = {

    'Alice': {
        'phone': '2341',
        'addr': 'Foo drive 23'
    },

    'Beth': {
        'phone': '9102',
        'addr': 'Bar street 42'
    },

    'Cecil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }

}

labels = {
    'phone': 'phone number',
    'addr': 'address'
}

name = input('Name: ')

# Are we looking for a phone number or an address?
request = input('Phone number (p) or address (a)? ')

# Use the correct key:
key = request # In case the request is neither 'p' nor 'a'
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'

# Use get to provide default values:
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')

print("{}'s {} is {}.".format(name, label, result))

运行结果如下:

Name: Gumby
Phone number (p) or address (a)? batting average
Gumby's batting average is not available.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 从今天开始我给自己定一个任务目标,每天的话至少发表1000字,这个对我来说是很有挑战性的,怎么去完成,我相信只要行...
    lj451698阅读 163评论 0 0
  • 有下列情形之一的,评标委员会应当否决其投标:【开标后才发现的】 (1)投标文件未按招标文件要求经投标人盖章和单位负...
    功能美阅读 497评论 0 0
  • 投射我儿读书明理,修身做人,每天阳光快乐,情绪平和稳定,越来越会调节自己的情绪和压力。 投射我儿对家人、他人、社会...
    花开生两面阅读 90评论 0 0
  • 今日体验,用心服务好客户,把一个环节,关键点,把控到位,就会有收获。 核心,流程是基础。 用,人情世故是铺垫,专业...
    王海博阅读 122评论 0 0
  • 冰山:2022.1.30 1.事件:忙年 2.感受:累,乏,充实,高兴 (情绪如何转化或使用) 3.想法: 一年一...
    可爱的小刺猬阅读 386评论 0 0

友情链接更多精彩内容