Home > Software engineering >  Use max and filter a list of dicts at the same time
Use max and filter a list of dicts at the same time

Time:12-28

I'm trying to filter a list of dicts and at the same time, use the max function to get the greatest value from this list based on a key/value:

closest_objects = [
    obj for obj in my_list
    if obj['start_date'].date() <= today
]

closest_object = max(
    closest_objects, key=lambda obj: obj['start_date']
)

return closest_object['todo_on_this_date']

But I want to know if there is a better way to implement this code if there is the fastest way or a simplified way.

CodePudding user response:

Using filter and max would look something like this:

max(
    filter(lambda _: _["start_date"].date() <= today, my_list), 
    key=lambda _: _["start_date"]
)

CodePudding user response:

You can use generator expressions to avoid explicitly construct the filtered list:

closest_object = max((obj for obj in my_list if obj['start_date'].date() <= today),
                     key=lambda obj: obj['start_date'])
  • Related