5

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
Enigmatic
  • 3,902
  • 6
  • 26
  • 48

2 Answers2

7
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

Afsal Salim
  • 486
  • 3
  • 14
2

For Python3, I believe that using the Pytz built-in module will be easier

>> import pytz
>> print(pytz.country_names['tn'])
Tunisia
Mahrez BenHamad
  • 1,791
  • 1
  • 15
  • 21