python-countries
Country Database in Python
- name
- currency
- flag
- official_languages
- ...
See ggicci/countries for the full list of the properties.
Install
pip install country-database
Usage
Load all countries
from country_database import load_countries
CountryIndex = load_countries()
print(CountryIndex.CAN.alpha2_code)
print(CountryIndex.CAN.name)
print(CountryIndex.CAN.name.to_locale("zh"))
CountryIndexZh = load_countries(locale="zh")
print(CountryIndexZh.CAN.name)
print(CountryIndexZh.CAN.name.to_locale("en"))
Load one country
from country_database import load_country
ca = load_country("CA")
print(ca.name)
Load a custom list of countries
from dataclasses import dataclass
from country_database import CountryProperties, load_countries_generic
@dataclass(frozen=True)
class MyCountryIndex:
CAN: CountryProperties
USA: CountryProperties
CHN: CountryProperties
CountryIndex = load_countries_generic(MyCountryIndex)
Add custom properties to a country
The default database is ggicci/countries.
You can add your own data and load them easily by instantiate a DataLoader and pass it to the load_countries*
, load_country*
or just merge your database to the default_dataloader
.
from pathlib import Path
from dataclasses import dataclass
from country_database import (
CountryProperties,
DataLoader,
FullCountryIndex,
Property,
)
CUSTOM_DATA_DIR = Path("/path/to/your/custom/data/dir")
@dataclass(frozen=True)
class MyCountry(CountryProperties):
custom_field_1: Property
custom_field_2: Property
loader = DataLoader()
loader.merge_database(CUSTOM_DATA_DIR)
CountryIndex = load_countries_generic(FullCountryIndex[MyCountry], loader=loader)
from country_database import default_dataloader
default_dataloader.merge_database(CUSTOM_DATA_DIR)
CountryIndex = load_countries_generic(FullCountryIndex[MyCountry])