How to convert country names to ISO 3166-1 alpha-2 values, using python

There is a module called pycountry.

Here’s an example code:

import pycountry

input_countries = ['American Samoa', 'Canada', 'France']

countries = {}
for country in pycountry.countries:
    countries[country.name] = country.alpha_2

codes = [countries.get(country, 'Unknown code') for country in input_countries]

print(codes)  # prints ['AS', 'CA', 'FR']

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)