2

I am writing a script that prompts the user for a state name. the script checks if the state is actually in the dictionary and gives back the capital. If the state does not in the dic, it states that isn't in the dictionary. I tried try except with KeyError but Python still gives me an error. What did I do wrong?

state_dictionary = {'Colorado': 'Denver', 'Alaska': 'Juneau', 'California': 'Sacramento',
                       'Georgia': 'Atlanta', 'Kansas': 'Topeka', 'Nebraska': 'Lincoln',
                       'Oregon': 'Salem', 'Texas': 'Austin', 'New York': 'Albany'}

if True:
    search_state=input("What is the State of the Capital you want to know? ")
    try: 
        state_dictionary[search_state]
    except KeyError: 
        print ('No such a State')
    print (state_dictionary[search_state]) 

What is the State of the Capital you want to know? Italia
No such a State

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-38-c6d25bb66225> in <module>()
     13     except KeyError:
     14         print ('No such a State')
---> 15     print (state_dictionary[search_state])

KeyError: 'Italia'

4 Answers 4

3

You have a dictionary, you can just use state_dictionary.get(key) to not throw errors and get none if it doesn't exist. Better than having to try catch.

Sign up to request clarification or add additional context in comments.

Comments

2

The error is actually coming up, at the end of your code you are doing this:

print (state_dictionary[search_state])

So, you caught your exception, and then continued your code, by still trying to access the state that does not exist.

Just put the print in your try, after you try to access the state_dictionary. It will only get there if it works. Furthermore, don't make your call twice. Store your result in a variable and then print the result:

try:
    capital = state_dictionary[search_state]
    print (capital)
except KeyError:
    print ('No such a State')

Furthermore, you can look at this another way. You can use the in keyword to check if the entry exists in the dictionary:

search_state=input("What is the State of the Capital you want to know? ")
if search_state in state_dictionary:
    print (state_dictionary[search_state])
else:
    print ('No such a State {}'.format(search_state))

One area of improvement you can also do, is that you are now expecting the exact casing to match. I suggest you change the entries in your dictionary to all lowercase, and when you get your input, force the check to be lowercase as well, so if you enter "texas", you will actually match it properly. As is now, if you enter "texas", it will not match "Texas".

So, can now do (note the call for search_state.lower()):

state_dictionary = {'colorado': 'Denver', 'alaska': 'Juneau', 'california': 'Sacramento',
                       'georgia': 'Atlanta', 'Kansas': 'Topeka', 'nebraska': 'Lincoln',
                       'oregon': 'Salem', 'texas': 'Austin', 'new york': 'Albany'}

try:
    capital = state_dictionary[search_state.lower()]
    print (capital)
except KeyError:
    print ('No such a State')

Comments

1

You do indeed try to implement a try, but since you then still make a call to state_dictionary[search_state] in your print statement, it still errors out.

Try:

state_dictionary = {'Colorado': 'Denver', 'Alaska': 'Juneau', 'California': 'Sacramento',
                       'Georgia': 'Atlanta', 'Kansas': 'Topeka', 'Nebraska': 'Lincoln',
                       'Oregon': 'Salem', 'Texas': 'Austin', 'New York': 'Albany'}

if True:
    search_state=input("What is the State of the Capital you want to know? ")
    try: 
        state_dictionary[search_state]
        print (state_dictionary[search_state]) 
    except KeyError: 
        print ('No such a State')

Comments

-1

Add an 'else' statement to the try except. It will only execute if there is no exception:

try: 
    state_dictionary[search_state]
except KeyError: 
    print ('No such a State')
else:
    print (state_dictionary[search_state]) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.