[Python #7] create e39.py

This commit is contained in:
kjg 2020-06-08 23:16:29 +09:00
parent 2a54759604
commit d9a5e0250e
2 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,66 @@
# create a mapping of state to abbreviation
states = {
'Kyungsangdo': 'KS',
'Kangwondo': 'KW',
'Jeju': 'JE',
'Junlado': 'JL',
'Chungchungdo': 'CC'
}
# create a basic set of states and some cities in them
cities = {
'KS': 'Busan',
'JE': 'Jejusi',
'JL': 'Mokpo'
}
# add some more cities
cities['KW'] = 'Sokcho'
cities['CC'] = 'Chungju'
# print out some cities
print('-' * 10)
print("KS State has: ", cities['KS'])
print("KW State has: ", cities['KW'])
# print some states
print('-' * 10)
print("Kyungsangdo's abbreviation is: ", states['Kyungsangdo'])
print("Kangwondo's abbreviation is: ", states['Kangwondo'])
# do it by using the state then cities dict
print('-' * 10)
print("Jeju has: ", cities[states['Jeju']])
print("Junlado has: ", cities[states['Junlado']])
# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")

View File

@ -140,3 +140,5 @@ create calc.py
analysis sample codes
**** ex38
append list
**** ex39
How to use dictionary