Search code examples
pythontypeerror

Python - TypeError: '<' not supported between instances of 'NoneType' and 'float'


I have working on different problems on 'countries.json' data. So now I need to find the country with the smallest area. so I've loaded the countries data to 'country_data'. But some of the data does not have 'area'. so its returning 'None' when I try to iterate and find minimum area.I need to avoid returning of 'None'

I have getting the following error:

File "path/countries.json", line 70, in <module>
    smallest_country = min(country_data, key=get_area)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'NoneType' and 'float'

This is my code

def get_area(c):
    if c.get("area") is not None:
        return c.get("area")

smallest_country = min(country_data, key=get_area)
print(smallest_country.get("name"))

Solution

  • The problem with get_area(): If c.get("area") is None, the function does not return the area. In Python, it means returning None implicitly.

    What you want is to filter out those countries which does not have area:

    smallest_country = min(
        country['area'] for country in country_data if "area" in country
    )
    

    The above does two things at once:

    1. It filters out those countries which does not have "area", and
    2. It finds the minimum area

    Update

    It was my bad. The OP wanted the name of the smallest country, so here is the corrected code:

    smallest_country = min(
        (country for country in country_data if "area" in country),
        key=lambda country: country["area"],
    )
    print(smallest_country["name"])
    

    An alternative to using lambda is to use operator.itemgetter:

    import operator
    
    smallest_country = min(
        (country for country in country_data if "area" in country),
        key=operator.itemgetter("area"),
    )
    print(smallest_country["name"])