Raveendra
Raveendra

Reputation: 47

find dictionary with min value in a list of dictionaries for a given key

I'm new to python and trying to find a solution to the problem:

The problem is to write a function that scans the array of records and returns the record that has the minimum value for a specified key. Records that do not contain the specified key are considered to have value 0 for the key.

Note that keys may map to negative values!

My solution:

def min_by_key(k,ld):
    min_val=min([d.get(k,0) for d in ld])
    for dt in ld:
        if dt.get(k,0)==min_val:            
            return dt


assert min_by_key("a", [{"a": 1, "b": 2}, {"a": 2}]) == {"a": 1, "b": 2} 
assert min_by_key("a", [{"a": 2}, {"a": 1, "b": 2}])  == {"a": 1, "b": 2} 
assert min_by_key("b", [{"a": 1, "b": 2}, {"a": 2}]) == {"a": 2} 
assert min_by_key("a", [{}]) == {} 
assert min_by_key("b", [{"a": -1}, {"b": -1}]) == {"b": -1} 

It is working but need to know is there any better way to do this.

Upvotes: 1

Views: 177

Answers (2)

Prem Anand
Prem Anand

Reputation: 2537

Just use min with key that compares key value k

>>> def min_by_key(k,ld):
...     return min(ld, key=lambda d: d.get(k, 0))
... 
>>> 

All your asserts pass

>>> assert min_by_key("a", [{"a": 1, "b": 2}, {"a": 2}]) == {"a": 1, "b": 2} 
>>> assert min_by_key("a", [{"a": 2}, {"a": 1, "b": 2}])  == {"a": 1, "b": 2} 
>>> assert min_by_key("b", [{"a": 1, "b": 2}, {"a": 2}]) == {"a": 2} 
>>> assert min_by_key("a", [{}]) == {} 
>>> assert min_by_key("b", [{"a": -1}, {"b": -1}]) == {"b": -1} 
>>> 

Upvotes: 2

Riccardo Bucco
Riccardo Bucco

Reputation: 15374

This is as simple as this:

def min_by_key(key, dicts):
    return min(dicts, key=lambda d: d.get(key, 0))

In this way you can sort by key, and in case there is no such value in a dict 0 is used.

Upvotes: 1

Related Questions