BenF97 BenF97 - 18 days ago 12
Python Question

Get country code using pycountry from a user input

I am trying to convert a country name to the desired country code.

For example:

United Kingdom : UK


I have attempted the following:

import pycountry
user_input = raw_input(': ')
mapping = {country.name: country.alpha2 for country in pycountry.countries}
print mapping.get(user_input)


I believe I may have misunderstood the documentation, since I receive the following error:

mapping = {country.name: country.alpha2 for country in pycountry.countries}
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pycountry/db.py", line 22, in __getattr__
raise AttributeError
AttributeError

Answer
import pycountry
user_input = raw_input(': ')
mapping = {country.name: country.alpha_2 for country in pycountry.countries}
print mapping.get(user_input)

is the correct way you are using 'alpha2' instead of alpha_2

Comments