How to get the country name from the 2-letter country code (alpha-2) in Python

1 Answer

0 votes
# ------------------------------------------------------------
# get_country_name
# Receives a 2‑letter ISO country code and returns the
# corresponding country name.
#
# Uses a dictionary for O(1) lookups.
# Input is normalized to uppercase to ensure consistent matching.
# Returns None if the code is not found.
# ------------------------------------------------------------
def get_country_name(alpha2: str) -> str | None:
    # Static lookup table; extend as needed
    country_map = {
        "CA": "Canada",
        "CN": "China",
        "DE": "Germany",
        "FR": "France",
        "GB": "United Kingdom",
        "KR": "South Korea",
        "IN": "India",
        "JP": "Japan",
        "US": "United States",
    }

    # Normalize input
    code = alpha2.strip().upper()

    # Lookup
    return country_map.get(code)


# ------------------------------------------------------------
# main
# Demonstrates the lookup function with several sample codes.
# ------------------------------------------------------------
def main() -> None:
    codes = ["US", "GB", "FR", "JP", "ZZ"]  # ZZ is intentionally invalid

    for code in codes:
        name = get_country_name(code)

        if name is not None:
            print(f"{code} → {name}")
        else:
            print(f"{code} → (invalid code)")



if __name__ == "__main__":
    main()


"""
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

"""

 



answered Sep 19 by avibootz
...