pycountry icon indicating copy to clipboard operation
pycountry copied to clipboard

Cannot find/lookup "UK" for United Kingdom

Open martinandrovich opened this issue 1 year ago • 3 comments

When trying to find "UK" using pycountry version 24.6.1, I cannot get a match for "United Kingdom". When using fuzzy search, the first results are "Uganda", "Ukraine", and "Japan". The desired lookup is Country(alpha_2='GB', alpha_3='GBR', flag='🇬🇧', name='United Kingdom', numeric='826', official_name='United Kingdom of Great Britain and Northern Ireland').

My code:

def lookup_country_code(name: str, *, allow_fuzzy: bool = True) -> str | None:
    """Lookup `ISO 3166-1 A-2` country code by country `name` using `pycountry`."""

    import pycountry

    if country := pycountry.countries.get(name=name):
        return country.alpha_2

    try:
        return pycountry.countries.lookup(name).alpha_2
    except LookupError:
        pass

    try:
        return pycountry.countries.search_fuzzy(query=name)[0].alpha_2 if allow_fuzzy else None
    except (LookupError, IndexError):
        return None

martinandrovich avatar Jun 13 '24 06:06 martinandrovich

Has there been any update on this?

RemDelaporteMathurin avatar Feb 11 '25 13:02 RemDelaporteMathurin

Hi @zware I'm trying to get to grips with pycountry but I ran into this issue where UK is converted to Uganda... similarly I can't lookup("germany") as it returns None... Is there something I'm missing here?

RemDelaporteMathurin avatar Feb 14 '25 10:02 RemDelaporteMathurin

lookup("germany") works fine for me:

>>> import pycountry
>>> pycountry.__version__
'24.6.1'
>>> pycountry.countries.lookup("germany")
Country(alpha_2='DE', alpha_3='DEU', flag='🇩🇪', name='Germany', numeric='276', official_name='Federal Republic of Germany')

The UK issue is a tricky one, since "UK" doesn't actually appear anywhere in the record for the United Kingdom. However, I've opened #254 to try to improve the situation. I'm not sure what it might make worse, though.

zware avatar Feb 16 '25 17:02 zware