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.
pip install pycountryVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to retrieve country and language information using specific ISO codes and how to use the more flexible `lookup()` method for searching across different name attributes.
Always check for attribute existence using `getattr(obj, 'attribute_name', default_value)` or handle `AttributeError` explicitly. Prefer `pycountry.countries.lookup()` for flexible name-based searches, which returns the most relevant match.
Understand that `pycountry` is a data consumer, not a data source for ISO standards. For political or data accuracy issues, upstream sources (ISO, Debian) should be consulted.
Ensure your project runs on Python 3.8 or newer. The current `pycountry` version requires Python >=3.10.
Use `getattr(obj, 'attribute_name', default_value)` to safely access potentially missing attributes, or implement `try-except AttributeError`. For searching, use `pycountry.collection.lookup('search_string')` as it provides a robust search across various naming attributes and handles unicode normalization.Ensure pycountry is installed using pip: `pip install pycountry`. If using a virtual environment, activate it before installing.
Use the `get()` method with a default fallback (e.g., `pycountry.countries.get(alpha_2='XX', default=None)`) or wrap the lookup in a `try-except KeyError` block. Verify that the key name is correct (e.g., `alpha_2` for ISO 3166-1 alpha-2 codes).
Use `getattr()` with a default value (e.g., `getattr(country, 'common_name', country.name)`) or check for the attribute's existence using `hasattr(country, 'common_name')` before accessing it. Ensure you are using the correct, up-to-date attribute names (e.g., 'alpha_3' for alpha-3 codes).
For PyInstaller, you need to explicitly include `pycountry`'s metadata in the `.spec` file. Add `from PyInstaller.utils.hooks import copy_metadata` at the top and modify the `datas` array in the `Analysis` section to include `datas=copy_metadata('pycountry'),`.No dependency data recorded yet.