From d9a5e0250e55c8384c87cac5d44822217a1e4a4e Mon Sep 17 00:00:00 2001 From: kjg Date: Mon, 8 Jun 2020 23:16:29 +0900 Subject: [PATCH] [Python #7] create e39.py --- kjg/python-the-hard-way/e39.py | 66 ++++++++++++++++++++++++++++++++++ kjg/python.org | 2 ++ 2 files changed, 68 insertions(+) create mode 100644 kjg/python-the-hard-way/e39.py diff --git a/kjg/python-the-hard-way/e39.py b/kjg/python-the-hard-way/e39.py new file mode 100644 index 0000000..087d013 --- /dev/null +++ b/kjg/python-the-hard-way/e39.py @@ -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}") + + diff --git a/kjg/python.org b/kjg/python.org index 46a7c3a..66ab96d 100644 --- a/kjg/python.org +++ b/kjg/python.org @@ -140,3 +140,5 @@ create calc.py analysis sample codes **** ex38 append list +**** ex39 +How to use dictionary