ex39.py

 1 # create a mapping of state to abbreviation
 2 states = {
 3     'Oregon': 'OR',
 4     'Florida': 'FL',
 5     'California': 'CA',
 6     'New York': 'NY',
 7     'Michigan': 'MI'
 8 }
 9 
10 #ctrat a basic set of states and some cities in them
11 cities = {
12     'CA': 'San Francisco',
13     'MI': 'Detroit',
14     'FL': 'Jacksonville'
15 }
16 
17 #add some more cities
18 
19 cities['NY'] = 'New York'
20 cities['OR'] = 'Portland'
21 
22 #Print out some cities
23 print ('-' * 10)
24 print ("NY State has: ", cities['NY'])
25 print ("OR state has: ", cities['OR'])
26 
27 #print some state
28 print ('-' * 10)
29 print ("Florida's abbreviation is: ", states['Florida'])
30 print ("Michigan's abbreviation is: ", states['Michigan'])
31 
32 #do it by using the state then cities dict
33 print ('-' * 10)
34 print ("Michigan has: ", cities[states['Michigan']])
35 print ("Florida has: ",cities[states['Florida']])
36 
37 #print every city in state
38 print ('-' * 10)
39 for abbrev, city in cities.items():
40     print ("%s has the city %s" % (
41         abbrev,city))
42 
43 # now do both at the same time
44 print ('-' * 10)
45 for state, abbrev in states.items():
46     print ("%s state is abbreviated %s and has city %s." %(
47         state,abbrev,cities[abbrev]))
48 
49 if not state:
50     print ("Sorry, no Texas.")
51 
52 # get a city with a default value
53 city = cities.get('TX', 'Does NOT Exist')
54 print ("The city for the state 'TX' is:%s" % city)

 

posted @ 2016-11-25 23:53  听风呤  阅读(211)  评论(0编辑  收藏  举报