Python_6

  1. 1.
>>> PhoneBook={'Beth':'1234','Alice':'1902'}
>>> PhoneBook['Beth']
'1234'

一个简单的字典。

  1. 2.
>>> items=[('name','Bob'),('age','42')]
>>> d=dict(items)
>>> d
{'age': '42', 'name': 'Bob'}
>>> d['age']
'42'
>>> d=dict(name='Bob',age='42')
>>> d
{'age': '42', 'name': 'Bob'}

使用dict函数创建字典的方法。

  1. 3.
# 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 = raw_input('Name: ')

# Are we looking for a phone number or an address?
request = raw_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's %s is %s." % \
    (name, labels[key], people[name][key])

People那里使用了两重字典,后面的输出用到了格式化输出。

输出结果范例:

Name: Alice
Phone number (p) or address (a)? a
Alice's address is Foo drive 23.

这里字典方法有很多,不再详细介绍。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值