pythoniso

How could I define a function `lookup_country_iso_codes` which returns the 2-digit and 3-digit ISO country code


Here is the question:

Define a function lookup_country_iso_codes which returns the 2-digit and 3-digit ISO country code given the name of country, based on countries.json in working directory.

def lookup_country_iso_codes(country: str) -> tuple:
   """
    >>> lookup_country_iso_codes("Taiwan")
    ('TW', 'TWN')
    >>> lookup_country_iso_codes("Japan")
    ('JP', 'JPN')
    >>> lookup_country_iso_codes("Lithuania")
    ('LT', 'LTU')
    >>> lookup_country_iso_codes("Slovenia")
    ('SI', 'SVN')
    """

And here is a part of the countries.json:

[{ "name" : "Afghanistan", "iso2": "AF", "iso3" : "AFG", "numeric": "004" }, { "name" : "South Africa", "iso2": "ZA", "iso3" : "ZAF", "numeric": "710" }, { "name" : "Åland Islands", "iso2": "AX", "iso3" : "ALA", "numeric": "248"}]

I keep getting AssertionError: Tuples differ: (None, None) != ('TW', 'TWN') and I don't know what the problem is. Thank you very much!


I'm sorry that I didn't attach the code I wrote (it was my first time using this website to ask questions, so I didn't quite understand the relevant regulations). The following is the code I originally wrote.

import json

def lookup_country_iso_codes(country: str) -> tuple:
    with open('countries.json', 'r', encoding='utf-8') as file:
        countries_data = json.load(file)

    if country.strip().lower() == "taiwan":
        return 'TW', 'TWN'

    for entry in countries_data:
        if entry['name'].strip().lower() == country.strip().lower():
            return entry.get('alpha2Code'), entry.get('alpha3Code')

    return None, None

Solution

  • import json
    
    def lookup_country_iso_codes(country: str) -> tuple:
        # Load the JSON file
        with open('countries.json') as file:
            countries = json.load(file)
    
        # Iterate through countries and match the specified country name
        for c in countries:
            if c['name'] == country:
                # Return 2-digit and 3-digit ISO codes when a match is found
                return c['iso2'], c['iso3']
    
        # If the country is not found, return None for both values
        return None, None
    
    # Example usage of the function
    print(lookup_country_iso_codes("Taiwan"))  # ('TW', 'TWN')
    print(lookup_country_iso_codes("Japan"))   # ('JP', 'JPN')
    

    An AssertionError suggests that the function is not finding the specified country in your countries.json data. This could be due to a few reasons.

    1. There could be a mismatch in country names. Make sure that the name in your JSOn file matches exactly the one you are searching for. For example, if your JSON file has "Republic of China (Taiwan)" instead of "Taiwan", the function won't find a match for "Taiwan".
    2. Make sure that your countries.json file is in the correct directory and is being read properly.
    3. Make sure that the JSON structure in your file matches the format in your function.
    4. If your JSON file has encoding issues or special characters, it might affect the string matching.

    Try the modified function above.