|
| 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 | + |
| 11 | +# create a basic set of states and some cities in them |
| 12 | +cities = [ |
| 13 | + 'CA': 'San Francisco', |
| 14 | + 'MI': 'Detroit', |
| 15 | + 'FL': 'Jacksonville' |
| 16 | +] |
| 17 | +# add some more cities |
| 18 | +cities['NY'] = 'New York' |
| 19 | +cities['OR'] = 'Portland' |
| 20 | + |
| 21 | +# print out some cities |
| 22 | +print '- ' * 10 |
| 23 | +print "NY State has: ", cities['NY'] |
| 24 | +print "OR State has: ", cities['OR'] |
| 25 | +# print some states |
| 26 | +print '- ' * 10 |
| 27 | +print "Michigan's abbreviation is: ", states['Michigan'] |
| 28 | +print "Florida's abbreviation is: ", states['Florida'] |
| 29 | +# do it by using the state then cities dict |
| 30 | +print '- ' * 10 |
| 31 | +print "Michigan has: ", cities[states['Michigan']] |
| 32 | +print "Florida has: ", cities[states['Florida']] |
| 33 | +# print every state abbreviation |
| 34 | +print '- ' * 10 |
| 35 | +for state, abbrev in states.items(): |
| 36 | + print "%s is abbreviated %s" % (state, abbrev) |
| 37 | +# print every city in state |
| 38 | +print '- ' * 10 |
| 39 | +for abbrev, city in cities.items(): |
| 40 | + print "%s has the city %s" % (abbrev, city) |
| 41 | +# now do both at the same time |
| 42 | +print '- ' * 10 |
| 43 | +for state, abbrev in states.items(): |
| 44 | + print "%s state is abbreviated %s and has city %s" % ( |
| 45 | +state, abbrev, cities[abbrev]) |
| 46 | +print '- ' * 10 |
| 47 | +# safely get an abbreviation by state that might not be there |
| 48 | +state = states.get('Texas', None) |
| 49 | +if not state: |
| 50 | + print "Sorry, no Texas." |
| 51 | +# get a city with a default value |
| 52 | +city = cities.get('TX', 'Does Not Exist') |
| 53 | +print "The city for the state 'TX' is: %s" % city |
0 commit comments