I know this has been asked 8 months ago, but here is a pretty good solution in case you are coming from Google (just like me).

You can use the ISO standard library located here: https://pypi.python.org/pypi/iso3166/

This piece of code is taken from that link in case you get a 404 Error some time in the future:

Installation:

pip install iso3166

Country Details:

>>> from iso3166 import countries
>>> countries.get('us')
Country(name=u'United States', alpha2='US', alpha3='USA', numeric='840')
>>> countries.get('ala')
Country(name=u'\xc5land Islands', alpha2='AX', alpha3='ALA', numeric='248')
>>> countries.get(8)
Country(name=u'Albania', alpha2='AL', alpha3='ALB', numeric='008')

Countries List:

>>> from iso3166 import countries
>>> for c in countries:
>>>       print(c)
Country(name=u'Afghanistan', alpha2='AF', alpha3='AFG', numeric='004')
Country(name=u'\xc5land Islands', alpha2='AX', alpha3='ALA', numeric='248')
Country(name=u'Albania', alpha2='AL', alpha3='ALB', numeric='008')
Country(name=u'Algeria', alpha2='DZ', alpha3='DZA', numeric='012')
...

This package is compliant in case you want to follow the standardization proposed by ISO. According to Wikipedia:

ISO 3166 is a standard published by the International Organization for Standardization (ISO) that defines codes for the names of countries, dependent territories, special areas of geographical interest, and their principal subdivisions (e.g., provinces or states). The official name of the standard is Codes for the representation of names of countries and their subdivisions.

Hence, I strongly recommend using this library in all your apps in case you are working with Countries.

Hope this piece of data is useful for the community!

Answer from Martin Castro Alvarez on Stack Overflow
🌐
PyPI
pypi.org › project › pycountry
pycountry · PyPI
Specific countries can be looked up by their various codes and provide the information included in the standard as attributes: >>> germany = pycountry.countries.get(alpha_2='DE') >>> germany Country(alpha_2='DE', alpha_3='DEU', flag='🇩🇪', name='Germany', numeric='276', official_name='Federal Republic of Germany') >>> germany.alpha_2 'DE' >>> germany.alpha_3 'DEU' >>> germany.numeric '276' >>> germany.name 'Germany' >>> germany.official_name 'Federal Republic of Germany'
      » pip install pycountry
    
Published   Feb 17, 2026
Version   26.2.16
🌐
Medium
medium.com › @HeCanThink › pycountry-your-passport-to-iso-country-codes-names-and-more-2c39ef6668c0
PyCountry: Your Passport to ISO Country Codes, Names and More 🛂 | by Manoj Das | Medium
August 11, 2023 - Enumerating Countries: You can obtain a list of all countries recognized by the ISO standard and iterate through them using the countries module provided by the package. Country Validation: pycountry provides functions to validate and verify ...
🌐
Parseltongue
parseltongue.co.in › exploring-countries-with-the-pycountry-module-in-python
ParselTongue - Exploring Countries with the pycountry Module in Python
September 1, 2023 - import pycountry country_name = "India" country = pycountry.countries.get(name=country_name) print(country)
🌐
Snyk
snyk.io › advisor › pycountry › functions › pycountry.countries.get
How to use the pycountry.countries.get function in pycountry | Snyk
if not self.regions: self.set_regions() if not self.db_has_data(): self.populate_db() cur = self.conn.cursor() cur.execute("SELECT * FROM cities WHERE city_name IN (" + ",".join("?"*len(self.places)) + ")", self.places) rows = cur.fetchall() for row in rows: country = None try: country = pycountry.countries.get(alpha2=row[3]) country_name = country.name except KeyError, e: country_name = row[4] city_name = row[7] region_name = row[6] if city_name not in self.cities: self.cities.append(city_name) if country_name not in self.countries: self.countries.append(country_name) self.country_mentions.append((country_name,1)) if country_name not in self.country_cities: self.country_cities[country.name] = []
🌐
GitHub
github.com › pycountry › pycountry
GitHub - pycountry/pycountry: A Python library to access ISO country, subdivision, language, currency and script definitions and their translations. · GitHub
Specific countries can be looked up by their various codes and provide the information included in the standard as attributes: >>> germany = pycountry.countries.get(alpha_2='DE') >>> germany Country(alpha_2='DE', alpha_3='DEU', flag='🇩🇪', name='Germany', numeric='276', official_name='Federal Republic of Germany') >>> germany.alpha_2 'DE' >>> germany.alpha_3 'DEU' >>> germany.numeric '276' >>> germany.name 'Germany' >>> germany.official_name 'Federal Republic of Germany'
Starred by 964 users
Forked by 140 users
Languages   Python 90.8% | Makefile 8.9% | Nix 0.3%
🌐
ProgramCreek
programcreek.com › python › example › 50402 › pycountry.countries
Python Examples of pycountry.countries
You may also want to check out all available functions/classes of the module pycountry , or try the search function . ... def countries(output): """Generate JSON file containing all countries.""" import pycountry results = [] for country in pycountry.countries: results.append({ "type": "country", "key": country.alpha_2, "text": "{} ({})".format(country.name, country.alpha_2), }) with open(output, "w+") as f: json.dump(results, f, sort_keys=True, indent=2) click.echo("stored {} countries in {}".format(len(results), output))
Top answer
1 of 9
13

I know this has been asked 8 months ago, but here is a pretty good solution in case you are coming from Google (just like me).

You can use the ISO standard library located here: https://pypi.python.org/pypi/iso3166/

This piece of code is taken from that link in case you get a 404 Error some time in the future:

Installation:

pip install iso3166

Country Details:

>>> from iso3166 import countries
>>> countries.get('us')
Country(name=u'United States', alpha2='US', alpha3='USA', numeric='840')
>>> countries.get('ala')
Country(name=u'\xc5land Islands', alpha2='AX', alpha3='ALA', numeric='248')
>>> countries.get(8)
Country(name=u'Albania', alpha2='AL', alpha3='ALB', numeric='008')

Countries List:

>>> from iso3166 import countries
>>> for c in countries:
>>>       print(c)
Country(name=u'Afghanistan', alpha2='AF', alpha3='AFG', numeric='004')
Country(name=u'\xc5land Islands', alpha2='AX', alpha3='ALA', numeric='248')
Country(name=u'Albania', alpha2='AL', alpha3='ALB', numeric='008')
Country(name=u'Algeria', alpha2='DZ', alpha3='DZA', numeric='012')
...

This package is compliant in case you want to follow the standardization proposed by ISO. According to Wikipedia:

ISO 3166 is a standard published by the International Organization for Standardization (ISO) that defines codes for the names of countries, dependent territories, special areas of geographical interest, and their principal subdivisions (e.g., provinces or states). The official name of the standard is Codes for the representation of names of countries and their subdivisions.

Hence, I strongly recommend using this library in all your apps in case you are working with Countries.

Hope this piece of data is useful for the community!

2 of 9
12

You can use pycountry to get a list of all the countries:

pip install pycountry 

Or you can use this dictionary:

Country = [
    ('US', 'United States'),
    ('AF', 'Afghanistan'),
    ('AL', 'Albania'),
    ('DZ', 'Algeria'),
    ('AS', 'American Samoa'),
    ('AD', 'Andorra'),
    ('AO', 'Angola'),
    ('AI', 'Anguilla'),
    ('AQ', 'Antarctica'),
    ('AG', 'Antigua And Barbuda'),
    ('AR', 'Argentina'),
    ('AM', 'Armenia'),
    ('AW', 'Aruba'),
    ('AU', 'Australia'),
    ('AT', 'Austria'),
    ('AZ', 'Azerbaijan'),
    ('BS', 'Bahamas'),
    ('BH', 'Bahrain'),
    ('BD', 'Bangladesh'),
    ('BB', 'Barbados'),
    ('BY', 'Belarus'),
    ('BE', 'Belgium'),
    ('BZ', 'Belize'),
    ('BJ', 'Benin'),
    ('BM', 'Bermuda'),
    ('BT', 'Bhutan'),
    ('BO', 'Bolivia'),
    ('BA', 'Bosnia And Herzegowina'),
    ('BW', 'Botswana'),
    ('BV', 'Bouvet Island'),
    ('BR', 'Brazil'),
    ('BN', 'Brunei Darussalam'),
    ('BG', 'Bulgaria'),
    ('BF', 'Burkina Faso'),
    ('BI', 'Burundi'),
    ('KH', 'Cambodia'),
    ('CM', 'Cameroon'),
    ('CA', 'Canada'),
    ('CV', 'Cape Verde'),
    ('KY', 'Cayman Islands'),
    ('CF', 'Central African Rep'),
    ('TD', 'Chad'),
    ('CL', 'Chile'),
    ('CN', 'China'),
    ('CX', 'Christmas Island'),
    ('CC', 'Cocos Islands'),
    ('CO', 'Colombia'),
    ('KM', 'Comoros'),
    ('CG', 'Congo'),
    ('CK', 'Cook Islands'),
    ('CR', 'Costa Rica'),
    ('CI', 'Cote D`ivoire'),
    ('HR', 'Croatia'),
    ('CU', 'Cuba'),
    ('CY', 'Cyprus'),
    ('CZ', 'Czech Republic'),
    ('DK', 'Denmark'),
    ('DJ', 'Djibouti'),
    ('DM', 'Dominica'),
    ('DO', 'Dominican Republic'),
    ('TP', 'East Timor'),
    ('EC', 'Ecuador'),
    ('EG', 'Egypt'),
    ('SV', 'El Salvador'),
    ('GQ', 'Equatorial Guinea'),
    ('ER', 'Eritrea'),
    ('EE', 'Estonia'),
    ('ET', 'Ethiopia'),
    ('FK', 'Falkland Islands (Malvinas)'),
    ('FO', 'Faroe Islands'),
    ('FJ', 'Fiji'),
    ('FI', 'Finland'),
    ('FR', 'France'),
    ('GF', 'French Guiana'),
    ('PF', 'French Polynesia'),
    ('TF', 'French S. Territories'),
    ('GA', 'Gabon'),
    ('GM', 'Gambia'),
    ('GE', 'Georgia'),
    ('DE', 'Germany'),
    ('GH', 'Ghana'),
    ('GI', 'Gibraltar'),
    ('GR', 'Greece'),
    ('GL', 'Greenland'),
    ('GD', 'Grenada'),
    ('GP', 'Guadeloupe'),
    ('GU', 'Guam'),
    ('GT', 'Guatemala'),
    ('GN', 'Guinea'),
    ('GW', 'Guinea-bissau'),
    ('GY', 'Guyana'),
    ('HT', 'Haiti'),
    ('HN', 'Honduras'),
    ('HK', 'Hong Kong'),
    ('HU', 'Hungary'),
    ('IS', 'Iceland'),
    ('IN', 'India'),
    ('ID', 'Indonesia'),
    ('IR', 'Iran'),
    ('IQ', 'Iraq'),
    ('IE', 'Ireland'),
    ('IL', 'Israel'),
    ('IT', 'Italy'),
    ('JM', 'Jamaica'),
    ('JP', 'Japan'),
    ('JO', 'Jordan'),
    ('KZ', 'Kazakhstan'),
    ('KE', 'Kenya'),
    ('KI', 'Kiribati'),
    ('KP', 'Korea (North)'),
    ('KR', 'Korea (South)'),
    ('KW', 'Kuwait'),
    ('KG', 'Kyrgyzstan'),
    ('LA', 'Laos'),
    ('LV', 'Latvia'),
    ('LB', 'Lebanon'),
    ('LS', 'Lesotho'),
    ('LR', 'Liberia'),
    ('LY', 'Libya'),
    ('LI', 'Liechtenstein'),
    ('LT', 'Lithuania'),
    ('LU', 'Luxembourg'),
    ('MO', 'Macau'),
    ('MK', 'Macedonia'),
    ('MG', 'Madagascar'),
    ('MW', 'Malawi'),
    ('MY', 'Malaysia'),
    ('MV', 'Maldives'),
    ('ML', 'Mali'),
    ('MT', 'Malta'),
    ('MH', 'Marshall Islands'),
    ('MQ', 'Martinique'),
    ('MR', 'Mauritania'),
    ('MU', 'Mauritius'),
    ('YT', 'Mayotte'),
    ('MX', 'Mexico'),
    ('FM', 'Micronesia'),
    ('MD', 'Moldova'),
    ('MC', 'Monaco'),
    ('MN', 'Mongolia'),
    ('MS', 'Montserrat'),
    ('MA', 'Morocco'),
    ('MZ', 'Mozambique'),
    ('MM', 'Myanmar'),
    ('NA', 'Namibia'),
    ('NR', 'Nauru'),
    ('NP', 'Nepal'),
    ('NL', 'Netherlands'),
    ('AN', 'Netherlands Antilles'),
    ('NC', 'New Caledonia'),
    ('NZ', 'New Zealand'),
    ('NI', 'Nicaragua'),
    ('NE', 'Niger'),
    ('NG', 'Nigeria'),
    ('NU', 'Niue'),
    ('NF', 'Norfolk Island'),
    ('MP', 'Northern Mariana Islands'),
    ('NO', 'Norway'),
    ('OM', 'Oman'),
    ('PK', 'Pakistan'),
    ('PW', 'Palau'),
    ('PA', 'Panama'),
    ('PG', 'Papua New Guinea'),
    ('PY', 'Paraguay'),
    ('PE', 'Peru'),
    ('PH', 'Philippines'),
    ('PN', 'Pitcairn'),
    ('PL', 'Poland'),
    ('PT', 'Portugal'),
    ('PR', 'Puerto Rico'),
    ('QA', 'Qatar'),
    ('RE', 'Reunion'),
    ('RO', 'Romania'),
    ('RU', 'Russian Federation'),
    ('RW', 'Rwanda'),
    ('KN', 'Saint Kitts And Nevis'),
    ('LC', 'Saint Lucia'),
    ('VC', 'St Vincent/Grenadines'),
    ('WS', 'Samoa'),
    ('SM', 'San Marino'),
    ('ST', 'Sao Tome'),
    ('SA', 'Saudi Arabia'),
    ('SN', 'Senegal'),
    ('SC', 'Seychelles'),
    ('SL', 'Sierra Leone'),
    ('SG', 'Singapore'),
    ('SK', 'Slovakia'),
    ('SI', 'Slovenia'),
    ('SB', 'Solomon Islands'),
    ('SO', 'Somalia'),
    ('ZA', 'South Africa'),
    ('ES', 'Spain'),
    ('LK', 'Sri Lanka'),
    ('SH', 'St. Helena'),
    ('PM', 'St.Pierre'),
    ('SD', 'Sudan'),
    ('SR', 'Suriname'),
    ('SZ', 'Swaziland'),
    ('SE', 'Sweden'),
    ('CH', 'Switzerland'),
    ('SY', 'Syrian Arab Republic'),
    ('TW', 'Taiwan'),
    ('TJ', 'Tajikistan'),
    ('TZ', 'Tanzania'),
    ('TH', 'Thailand'),
    ('TG', 'Togo'),
    ('TK', 'Tokelau'),
    ('TO', 'Tonga'),
    ('TT', 'Trinidad And Tobago'),
    ('TN', 'Tunisia'),
    ('TR', 'Turkey'),
    ('TM', 'Turkmenistan'),
    ('TV', 'Tuvalu'),
    ('UG', 'Uganda'),
    ('UA', 'Ukraine'),
    ('AE', 'United Arab Emirates'),
    ('UK', 'United Kingdom'),
    ('UY', 'Uruguay'),
    ('UZ', 'Uzbekistan'),
    ('VU', 'Vanuatu'),
    ('VA', 'Vatican City State'),
    ('VE', 'Venezuela'),
    ('VN', 'Viet Nam'),
    ('VG', 'Virgin Islands (British)'),
    ('VI', 'Virgin Islands (U.S.)'),
    ('EH', 'Western Sahara'),
    ('YE', 'Yemen'),
    ('YU', 'Yugoslavia'),
    ('ZR', 'Zaire'),
    ('ZM', 'Zambia'),
    ('ZW', 'Zimbabwe')
]

Update 2021: The module has been updated including shortcomings mentioned by @JurajBezručka

🌐
Readthedocs
pycountry-convert.readthedocs.io › en › latest
pycountry-convert — pycountry-convert 0.7.3 documentation
Extension of Python package pycountry providing conversion functions. ... Using country data derived from wikipedia, this package provides conversion functions between ISO country names, country-codes, and continent names. map_countries(cn_name_format="default", cn_extras={}): Return a dict of countries with key as country name (standard and official) with ISO 3166-1 values Alpha 2, Alpha 3, and Numeric.
Top answer
1 of 4
4

Use pycountry.countries.lookup

>>> pycountry.countries.lookup('Bolivia')
Country(alpha_2='BO', alpha_3='BOL', common_name='Bolivia', name='Bolivia, Plurinational State of', numeric='068', official_name='Plurinational State of Bolivia')
2 of 4
1

This, albeit not being elegant at all, worked for me:

def country_code_converter(input_countries):
    """
    :param input_countries: list containing the name of the countries (can be numpy array)
    :return: list with the ISO alpha 3 codes for the given input ('Unknown Country' if no match found)
    """
    countries = {}
    countries_official = {}
    countries_common = {}

    #loops over all of the countries contained in the pycountry library and populates dictionary
    for country in pycountry.countries:
        countries[country.name] = country.alpha_3

    #loops over the alpha_3 codes from the countries dictionary
    #populates dictionary containing official names and codes
    for alpha_3 in list(countries.values()):
        try:
            countries_official[pycountry.countries.get(alpha_3 = alpha_3).official_name] = alpha_3
        except:
            None
    #same for common names
    for alpha_3 in list(countries.values()):
        try:
            countries_common[pycountry.countries.get(alpha_3 = alpha_3).common_name] = alpha_3
        except:
            None

    codes = []
    # appends ISO codes for all matches by trying different country name types
    # appends Unknown Country if no match found
    for i in input_countries:
        if i in countries.keys():
            codes.append(countries.get(i))

        elif i in countries_official.keys():
            codes.append(countries_official.get(i))

        elif i in countries_common.keys():
            codes.append(countries_common.get(i))

        else:
            codes.append('Unknown Country')
    return codes
Find elsewhere
🌐
PyTutorial
pytutorial.com › python-pycountry-understand-how-to-use-pycountry
PyTutorial | Python-pycountry | Understand How to Use pycountry
November 30, 2022 - countries = pycountry.countries # 👉️ Get All World Countries info countries_n = len(countries) # 👉️ Get number of countries print("Total:", countries_n)
🌐
GitHub
github.com › koldakov › pycountries
GitHub - koldakov/pycountries: Python library to access ISO country and currency standards. · GitHub
Python library to access ISO country and currency standards. - koldakov/pycountries
Author   koldakov
🌐
PyPI
pypi.org › project › pycountry-convert
pycountry-convert · PyPI
Extension of Python package pycountry providing conversion functions. ... Using country data derived from wikipedia, this package provides conversion functions between ISO country names, country-codes, and continent names. map_countries(cn_name_format="default", cn_extras={}): Return a dict of countries with key as country name (standard and official) with ISO 3166-1 values Alpha 2, Alpha 3, and Numeric.
      » pip install pycountry-convert
    
Published   Feb 18, 2018
Version   0.7.2
🌐
PyPI
pypi.org › project › pycountry-nopytest
pycountry-nopytest · PyPI
Specific countries can be looked up by their various codes and provide the information included in the standard as attributes: >>> germany = pycountry.countries.get(alpha2='DE') >>> germany <pycountry.db.Country object at 0x...> >>> germany.alpha2 u'DE' >>> germany.alpha3 u'DEU' >>> germany.numeric u'276' >>> germany.name u'Germany' >>> germany.official_name u'Federal Republic of Germany'
      » pip install pycountry-nopytest
    
Published   Jul 10, 2013
Version   0.16.dev0
🌐
GitHub
github.com › PEAT-AI › pycountry
GitHub - PEAT-AI/pycountry
Copy-paste the command ``` pip install -e git+https://github.com/PEAT-AI/pycountry.git#egg=pycountry ``` pycountry provides the ISO databases for the standards: 639-3 Languages 3166 Countries 3166-3 Deleted countries 3166-2 Subdivisions of countries 4217 Currencies 15924 Scripts The package includes a copy from Debian's `pkg-isocodes` and makes the data accessible through a Python API.
Author   PEAT-AI
🌐
GitHub
github.com › pycountry
pycountry · GitHub
pycountry has one repository available. Follow their code on GitHub.
🌐
Medium
medium.com › @richamonga86 › do-you-want-to-check-if-country-name-coming-in-your-data-is-correct-or-not-5583cee1b960
Do you want to check if Country Name coming in your data is correct or not? Here is a Python function that does it for you. | by Richa Monga | Medium
August 4, 2018 - This function uses ‘pycountry’ library of Python which contains ISO country names.It provides two-alphabet country name,three-alphabet country name,name,common name,official name and numeric country code.Sample is shown below: ... Fetch ‘country’ column from the data set as list and convert each element of the list into upper case so that we can do case insensitive comparison with list of countries ...
🌐
Python
bugs.python.org › file20989 › README.txt
README.txt
========= pycountry ========= pycountry provides the ISO databases for the standards: 639 Languages 3166 Countries 3166-2 Subdivisions of countries 4217 Currencies 15924 Scripts The package includes a copy from Debian's `pkg-isocodes` and makes the data accessible through a Python API.
🌐
GitLab
code.officialstatistics.org › rhui › pycountry › repository
README.rst · main · rhui / pycountry · GitLab - Snippets
A Python library to access ISO country, subdivision, language, currency and script definitions and their translations.
🌐
Cern
simple-repository.app.cern.ch › project › pycountry
pycountry · Python Simple Repository Browser
Specific countries can be looked up by their various codes and provide the information included in the standard as attributes: >>> germany = pycountry.countries.get(alpha_2='DE') >>> germany Country(alpha_2='DE', alpha_3='DEU', flag='🇩🇪', name='Germany', numeric='276', official_name='Federal Republic of Germany') >>> germany.alpha_2 'DE' >>> germany.alpha_3 'DEU' >>> germany.numeric '276' >>> germany.name 'Germany' >>> germany.official_name 'Federal Republic of Germany'