Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find lowest value in a list of dictionaries in python

I want to find and return the minimal value of an id in a string, for example:

find_min_id([{"nonid": "-222", "id": 0}, {"id": -101}])
-101
find_min_id([{’id’: 63, 'id': 42}])
42

So far I have this:

def find_min_id(list):
    return min(list)

but that gives:

{'id': -101}

and I only want the value of the lowest id.

like image 271
user2858846 Avatar asked Oct 27 '13 14:10

user2858846


2 Answers

Use the key parameter of min:

def find_min_id(l):
    return min(l, key=lambda d: d.get("id", float('inf')))["id"]

This actually finds the min id, and does it without creating a new list.

The only thing is, the elements in your list might not had an 'id' key. For that reason I had to use .get("id", float('inf')). Thus the function will return inf if there is no id key, which might not be desirable. What min() does when given an empty list is it throws an exception, so we'd probably like to do the same if none of the dicts we pass it have an 'id' key. In that case the min of a generator appoach might indeed be better:

def find_min_id(l):
    return min(d["id"] for d in l if "id" in d)

The other approach would be to check for inf as the result of min, but this is more cumbersome:

import math
def find_min_id(l):
    res = min(l, key=lambda d: d.get("id", float('inf')))["id"]
    if math.isinf(res):
        raise ValueError("No dict has an 'id' key")
    return res
like image 88
Claudiu Avatar answered Oct 27 '22 17:10

Claudiu


Another approach, but works where there is no id in the dictionary, and when there is no dictionary with an id at all:

def find_min_id(lst):
    ids = [d['id'] for d in lst if 'id' in d]
    return min(ids) if ids else None

Without exceptions, and without running min for artificially extended list (i.e. the answer which puts maximum floats where an entry isn't an id-entry).

like image 2
BartoszKP Avatar answered Oct 27 '22 17:10

BartoszKP