Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 347
MHS Avatar asked Apr 27 '13 14:04

MHS


People also ask

How can I get country code from country?

Use the Intl. DisplayNames() constructor to get a country name from a country code, e.g. new Intl. DisplayNames(['en'], {type: 'region'}).

What is Pycountry?

pycountry provides the ISO databases for the standards: 639-3 Languages. 3166 Countries. 3166-3 Deleted countries.

Is ISO a country code?

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 .


2 Answers

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'] 
like image 156
alecxe Avatar answered Oct 07 '22 02:10

alecxe


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.

like image 34
Ashwini Chaudhary Avatar answered Oct 07 '22 01:10

Ashwini Chaudhary