pycountry
pycountry is a Python library that provides access to various ISO standards databases, including ISO 3166 (countries and their subdivisions), ISO 639 (languages), ISO 4217 (currencies), and ISO 15924 (scripts). It acts as a pure wrapper around Debian's `pkg-isocodes` database, making this data accessible through a Python API, complete with translation files. The library is actively maintained, with data updates typically following the `pkg-isocodes` updates rather than a fixed release schedule. The current version is 26.2.16.
Warnings
- breaking In version 24.6.1, a fallback mechanism was removed. Previously, if `country.common_name` or `country.official_name` were unavailable, it would fall back to `country.name`. This fallback was reverted. Code relying on this implicit fallback will now raise `AttributeError` if the specific attribute is missing.
- gotcha The data in pycountry is a direct wrapper around Debian's `pkg-isocodes` database. This means `pycountry` itself does not accept direct contributions for changes to country, language, or currency data. Any required changes to the underlying ISO data must be addressed with ISO or Debian's `pkg-isocodes` project.
- deprecated Support for Python 3.6 and 3.7 was officially dropped in version 23.12.11.
- gotcha When retrieving objects, using `.get()` requires an exact match on a specified attribute (e.g., `alpha_2`, `name`). If an attribute like `official_name` or `common_name` might not always exist for all entries, direct access (e.g., `country.official_name`) can raise an `AttributeError`.
Install
-
pip install pycountry
Imports
- countries
import pycountry country = pycountry.countries.get(alpha_2='US')
- subdivisions
import pycountry subdivision = pycountry.subdivisions.get(code='US-CA')
- languages
import pycountry language = pycountry.languages.get(alpha_3='eng')
- currencies
import pycountry currency = pycountry.currencies.get(alpha_3='USD')
- scripts
import pycountry script = pycountry.scripts.get(alpha_4='Latn')
- historic_countries
import pycountry historic_country = pycountry.historic_countries.get(alpha_3='SUN')
- lookup
import pycountry country = pycountry.countries.lookup('United States')
Quickstart
import pycountry
# Get a country by its Alpha-2 code
try:
usa = pycountry.countries.get(alpha_2='US')
print(f"Country Name: {usa.name}, Alpha-3: {usa.alpha_3}")
except KeyError:
print("Country not found.")
# Get a language by its Alpha-3 code
try:
english = pycountry.languages.get(alpha_3='eng')
print(f"Language Name: {english.name}")
except KeyError:
print("Language not found.")
# Search for a country using a more flexible lookup
try:
bolivia_lookup = pycountry.countries.lookup('Bolivia')
print(f"Lookup for Bolivia: {bolivia_lookup.name}, Official: {getattr(bolivia_lookup, 'official_name', 'N/A')}")
except LookupError:
print("Bolivia not found via lookup.")