字典用{ }表示。。 表示mapping的关心。
例如: phonebook ={'Alice':'2314' , 'Beth': '9102' , 'Cecil':'3258' }
字典有两个特点:
x = []
x[42] = 'Footbar'
Traceback (most recent call last):
File " <stdin>" . line 1 , in?
IndexError: list assigment index out of range
x = {}
x[42] = 'Footbar'
x
{42: 'Foobar'}
people = {
'Alice' : {
'phone':'2341',
'addr':'Foo drive 23'
},
'Beth':{
'phone':'9102',
'addr': 'Bar street 42'
}
'Ceil':{
'phone':'3158'
'addr':'Baz avenue 90'
}
# 针对电话号码和地址使用的描述性标签, 会在打印输出的时候用到
lables = {
'phone': 'phone number',
'addr': 'address'
}
name = 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. lables[key],people[name][key])
python 中所有的索引符都是中括号。
}