- 1.
>>> PhoneBook={'Beth':'1234','Alice':'1902'}
>>> PhoneBook['Beth']
'1234'
一个简单的字典。
- 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函数创建字典的方法。
- 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.
这里字典方法有很多,不再详细介绍。