How to make a for loop with exception handling when key not in dictionary?
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>

<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</p>

<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose

countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')

for i in range(0, 5):
    while True:
        try:
            countr = input('Please enter country no. %d: ' %(i+1))
            countr = countr.title()            
            if countr in ex_dict.keys():
                print('Found the corresponding stock index! \n')
                countries.append(countr)
            break
        except KeyError:
            print('Country not found, please try again! \n')
</code></pre>

<p>From the <a href="https://wiki.python.org/moin/KeyError" rel="nofollow">doc</a></p>

<blockquote>
  <p>Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.</p>
</blockquote>

<p>In your piece of code if you want print a message when user inserts a key not present in the countries dict, you can simply add an else statement instead of catch exception.</p>

<p>You can change your code in this way:</p>

<pre><code>if countr in ex_dict.keys():
     print('Found the corresponding stock index! \n')
     countries.append(countr)
     break
else:
    print('Country not found, please try again! \n')
</code></pre>

python for-loop dictionary exception