import pycountry
user_input = raw_input(': ')
mapping = {country.name: country.alpha_2 for country in pycountry.countries}
print mapping.get(user_input)

is the correct way you are using 'alpha2' instead of alpha_2

Answer from Afsal Salim on Stack Overflow
🌐
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
🌐
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.
🌐
PyPI
pypi.org › project › pycountry
pycountry · PyPI
ISO country, subdivision, language, currency and script definitions and their translations
      » pip install pycountry
    
Published   Feb 17, 2026
Version   26.2.16
🌐
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
A Python library to access ISO country, subdivision, language, currency and script definitions and their translations. - pycountry/pycountry
Starred by 964 users
Forked by 140 users
Languages   Python 90.8% | Makefile 8.9% | Nix 0.3%
🌐
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 - No Geographical Information: While pycountry provides data related to ISO country codes, currencies, languages, and subdivisions, it doesn’t offer geographical data like coordinates, boundaries, or maps.
🌐
YouTube
youtube.com › watch
Map Country Names To Continent Codes/Name: Pycountry-convert ISO 3116-1 (Python) - YouTube
In this video I demonstrate how to map a country name to its continent with the pycountry module and python. The approach can also be used to convert country...
Published   January 26, 2021
🌐
Opensource.com
opensource.com › article › 20 › 4 › python-map-covid-19
How I use Python to map the global spread of COVID-19 | Opensource.com
April 21, 2020 - To generate the three-digit ISO 3 codes, use a small Python library called pycountry. Having generated these codes, you can add an extra column to our DataFrame and populate it with these codes. Finally, for the visualization, use the express module of a library called Plotly. This article uses what are called choropleth maps (available in Plotly) to visualize the worldwide spread of the disease.
Find elsewhere
🌐
Towards AI
towardsai.net › home › publication › latest › top 10 python libraries to work with geo-spatial data in 2022
Top 10 Python libraries to work with geo-spatial data in 2022 | Towards AI
July 26, 2023 - Moreover, I mark an available pycountry extension which is pycountry-convert, which provides quick and easy conversion functions between country names and codes, and also continents.
🌐
Kishimoto
paul.kishimoto.name › 2021 › 01 › handling-country-codes
Handling country codes - Paul Natsuo Kishimoto
January 28, 2021 - This function first uses country_map to correct data set idiosyncrasies, then uses pycountry.get() to look up a record using the ‘name’ field.
🌐
DEV Community
dev.to › leul12 › geo-coding-country-names-in-python-12ef
Geo coding Country Names in Python - DEV Community
April 6, 2023 - I needed to plot a map of their global operations, but all I had was a list of country names.After some research, I discovered that Python offers powerful tools for GEo-codding country names and obtaining their corresponding latitude and longitude coordinates. With the help of the geopy and pycountry libraries, I was able to quickly and easily convert the country names into coordinates, and plot them on a map using a mapping library like folium and plotly.
🌐
Messageix
docs.messageix.org › projects › models › en › latest › _modules › message_ix_models › util › pycountry.html
message_ix_models.util.pycountry — message-ix-models documentation
from functools import lru_cache #: Mapping from common, non-standard country names to exact field values occurring in #: the ISO 3166-1 database.
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
🌐
Pycountry
pycountry.com
PyCountry – My WordPress Blog
Supports adaptation of application ... accurate mapping, and seamless user experience across different regions and linguistic environments. Common setup problems occur due to missing or incorrect Python environments. Ensure pip, Poetry, or uv is properly installed and updated before installing Pycountry to avoid ...
🌐
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)
🌐
ProgramCreek
programcreek.com › python › example › 50402 › pycountry.countries
Python Examples of pycountry.countries
def test_lookup(): c = pycountry.countries g = c.get(alpha_2='DE') assert g == c.lookup('de') assert g == c.lookup('DEU') assert g == c.lookup('276') assert g == c.lookup('germany') assert g == c.lookup('Federal Republic of Germany') # try a generated field bqaq = pycountry.historic_countries.get(alpha_4='BQAQ') assert bqaq == pycountry.historic_countries.lookup('atb') german = pycountry.languages.get(alpha_2='de') assert german == pycountry.languages.lookup('De') euro = pycountry.currencies.get(alpha_3='EUR') assert euro == pycountry.currencies.lookup('euro') latin = pycountry.scripts.get(nam
🌐
Snyk
snyk.io › advisor › pycountry › pycountry code examples
Top 5 pycountry Code Examples | Snyk
if airport_type != 'large_airport' and airport_type != 'small_airport' and airport_type != 'medium_airport': continue airport_type = airport_type.split("_")[0] airport_name = row['name'].strip() airport_coords = { 'lat': float(row['latitude_deg']), 'lon': float(row['longitude_deg']) } airport_city = row['municipality'].strip() airport_url = row['home_link'].strip() airport_wiki = row['wikipedia_link'].strip() airport_icao = row['ident'].upper().strip() # Add a '.' after single uppercase letters airport_name = re.sub( r"\b([A-Z])(?![\w\-\.])", r"\1.", airport_name) country_iso_code = row['iso_c
🌐
GitHub
github.com › corbt › twitter-geo-visuals › blob › master › get_country_code.py
twitter-geo-visuals/get_country_code.py at master · corbt/twitter-geo-visuals
import pycountry · from incf.countryutils import transformations · · name_map = { "Venezuela": "Venezuela, Bolivarian Republic of", "South Korea": "Korea, Republic of", "North Korea": "Korea, Democratic People's Republic of", "Russia": "Russian Federation", "The Bahamas": "Bahamas", "Ivory Coast": u"C\xf4te d'Ivoire", "Bolivia": "Bolivia, Plurinational State of", "US Virgin Islands": "United States Minor Outlying Islands", "Syria": "Syrian Arab Republic", "Iran": "Iran, Islamic Republic of", "Taiwan": "Taiwan, Province of China", "Tanzania":
Author   corbt