Search code examples
pythonlambdafolium

Normal 'def' function instead of lambda


The following code produces a web map with countries colored by population which values come from world.json.

import folium

map=folium.Map(location=[30,30],tiles='Stamen Terrain')

map.add_child(folium.GeoJson(data=open('world.json', encoding='utf-8-sig'),
name="Unemployment",
style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))

map.save('file.html')

Link of world.json.

I was wondering if it's possible to use a normal function created with def instead of a lambda function as the value of the style_function argument. I tried creating a function for that:

def feature(x):
    file = open("world.json", encoding='utf-8-sig')
    data = json.load(file)
    population = data['features'][x]['properties']['POP2005']
    d ={'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}
    return d

However, I can't think of how to use it in style_function. Is this possible or is the lambda function irreplaceable here?


Solution

  • the style_function lambda can be replaced with a function like this:

    def style_function(x):
        return {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))
    

    Then you can just pass the function name to the kwarg:

    folium.GeoJson(
        data=...,
        name=...,
        style_function=style_function
    )