Find lowest value in a list of dictionaries in python
Question: 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.


Answer: 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
    

