练习39中,我们主要学会了运用字典。
下面来介绍一下书中没有介绍到的知识点:
stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}stuff字典中,‘name' 称为key(键),’Zed‘ 称为Value(值)。
本篇练习中,比较难理解的有以下几点:
1.dicts中,for循环的运用
for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev)这段程序当中,for循环和以往学的不一样,原因是我们使用的是字典中每个单元由分别由key和value组成,如:
states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }所以,这里的for循环中的字符串需要两个变量来赋值,in后面也要变成states.item()
2.dict.get()的运用
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。
dict.get(key, default=None)
- key -- 字典中要查找的键。
- default -- 如果指定键的值不存在时,返回该默认值值。
书中例题:
state = states.get('Texas') if not state: print "Sorry, no Texas." city = cities.get('TX', 'Does Not Exist') print "The city for the state 'TX' is: %s" % city
可另写以下程序来认识dict.get()的运用:
state = states.get('Oregon')
if state:
print "YES."
else:
print "NO."
city = cities.get('CA', 'Does Not Exist')
print "The city for the state 'CA' is: %s" % city
我们也可以把这段程序写得更有趣一些:
print "Let's search the abbreviation of the state."
a = raw_input( "state's name:")
state = states.get(a)
if state:
print "The %s 's abbrev is %s"% (a, state)
else:
print "Sorry, cannot find this state."
# get a city with a default value
print "Let's search which city is in the state."
b = raw_input( "state's abbreviation:")
city = cities.get(b, 'Does Not Exist')
print "The city for the state '%s' is: %s" % (b, city)