Python – Get minimum values (keys, values) in a list containing dictionaries

Get minimum values (keys, values) in a list containing dictionaries… here is a solution to the problem.

Get minimum values (keys, values) in a list containing dictionaries

I have a list with dictionary lines as follows:

queue = [{1: 0.39085439023582913, 2: 0.7138416909634645, 3: 0.9871959077954673}]

I’m trying to get it to return the minimum value and its key, so in this case it returns

1,0.39085439023582913

I tried it

min(queue, key=lambda x:x[1]) 

But this will only return the whole line like this: Any suggestions? Thanks!

{1: 0.39085439023582913, 2: 0.7138416909634645, 3: 0.9871959077954673}

Solution

If you want the minimum value for each dictionary in the list, you can use the following list inference:

[min(d.items(), key=lambda x: x[1]) for d in queue]

For your example return:

[(1, 0.39085439023582913)]

d.items() returns a list of tuples for dictionary d in the form (key, value). We then sort these tuples using values (in this case, x[1]).

If your data always exists as a list with a dictionary, you can also call .items() on the first element of the queue and find the minute:

print(min(queue[0].items(), key=lambda x:x[1]))
#(1, 0.39085439023582913)

Related Problems and Solutions