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?
Use the Intl. DisplayNames() constructor to get a country name from a country code, e.g. new Intl. DisplayNames(['en'], {type: 'region'}).
pycountry provides the ISO databases for the standards: 639-3 Languages. 3166 Countries. 3166-3 Deleted countries.
The ISO country codes are internationally recognized codes that designate every country and most of the dependent areas a two-letter combination or a three-letter combination; it is like an acronym, that stands for a country or a state. The country code is in use for example for the two-letter suffixes such as .
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']
You can use this csv file : country code list into a CSV.
import csv dic = {} with open("wikipedia-iso-country-codes.csv") as f: file= csv.DictReader(f, delimiter=',') for line in file: dic[line['English short name lower case']] = line['Alpha-2 code'] countries = ['American Samoa', 'Canada', 'France'] for country in countries: print(dic[country])
Will print:
AS CA FR
Few more alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With