1 people = {
2 'Alice' : {
3 'phone' : '2341',
4 'addr' : 'Foo drive 23'
5 },
6 'Beth' : {
7 'phone' : '9102',
8 'addr' : 'Bar street 42'
9 },
10 'Cecil' : {
11 'phone' : '3158',
12 'addr' : 'Baz avenue 90'
13 }
14 }
15
16 labels = {
17 'phone' : 'phone number',
18 'addr' : 'address'
19 }
20
21 name = input("Name:")
22
23 request = input("phone number(p) or address(a)?")
24
25 if request == 'p' : key = 'phone'
26 if request == 'a' : key = 'addr'
27
28 if name in people :
29 print("%s's %s is %s." % (name, labels[key], people[name][key]))
30
get 函数,提供默认值
1 people = {
2 'Alice' : {
3 'phone' : '2341',
4 'addr' : 'Foo drive 23'
5 },
6 'Beth' : {
7 'phone' : '9102',
8 'addr' : 'Bar street 42'
9 },
10 'Cecil' : {
11 'phone' : '3158',
12 'addr' : 'Baz avenue 90'
13 }
14 }
15
16 labels = {
17 'phone' : 'phone number',
18 'addr' : 'address'
19 }
20
21 name = input("Name:")
22
23 request = input("phone number(p) or address(a)?")
24
25 key = request
26 if request == 'p' : key = 'phone'
27 if request == 'a' : key = 'addr'
28
29 person = people.get(name, {})
30 label = labels.get(key, key)
31 result = person.get(key, 'not available')
32
33 print("%s's %s is %s." % (name, label, result))
34
posted on 2013-05-12 22:50
unixfy 阅读(144)
评论(0) 编辑 收藏 引用