Learn Python the hard way, ex40 字典,可爱的字典
1 #!/usr/bin/python 2 #coding:utf-8 3 cities ={'CA':'sf','MI':'dt','FL':'je'} #创建字典 4 cities['NY']='ny' #增加新元素 5 cities['OR']='pd' 6 7 def find_city(themap,state): 8 if state in themap: 9 return themap[state] 10 else: 11 return 'not found' 12 13 #ok pay attention 14 cities['_find'] =find_city 15 16 while True: 17 print "State?(ENTER to quit)", 18 state = raw_input('>>') 19 if not state: break 20 21 #this line is the most important ever!study! 22 city_found = cities['_find'](cities,state) 23 print city_found
Output
1 State?(ENTER to quit) >>CA 2 sf 3 State?(ENTER to quit) >>FL 4 je 5 State?(ENTER to quit) >>0 6 not found 7 State?(ENTER to quit) >>VT 8 not found 9 State?(ENTER to quit) >>