Enigmatic
Enigmatic

Reputation: 4148

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

Upvotes: 5

Views: 15905

Answers (2)

Mahrez BenHamad
Mahrez BenHamad

Reputation: 2096

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

>> import pytz
>> print(pytz.country_names['tn'])
Tunisia

Upvotes: 2

Afsal Salim
Afsal Salim

Reputation: 486

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

Upvotes: 7

Related Questions