这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!
文中例题:
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!
cities['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state : break
#this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
习题答案:
2、确实是无序的,所以dict中只能使用名字查找,但名字可以是数字或者字符。
3、items(),返回key和value
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
for abbreviate,city in cities.items():
print abbreviate,city
运行结果: