How to convert country names to ISO 3166-1 alpha-2 values, using python
Question: I have a list of countries like:

    
    
    countries=['American Samoa', 'Canada', 'France'...]
    

I want to convert them like this:

    
    
    countries=['AS', 'CA', 'FR'...]
    

Is there any module or any way to convert them?


Answer: There is a module called
[`pycountry`](https://pypi.python.org/pypi/pycountry).

Here's an example code:

    
    
    import pycountry
    
    
    input_countries = ['American Samoa', 'Canada', 'France']
    
    countries = {}
    for country in pycountry.countries:
        countries[country.name] = country.alpha2
    
    codes = [countries.get(country, 'Unknown code') for country in input_countries]
    
    print codes  # prints [u'AS', u'CA', u'FR']
    

