3

I have a list that holds a dictionary row like this:

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

I'm tryin to get it to return the smallest value along with its key, so in this case it would return

1,0.39085439023582913

I've tried using

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

but that just returns the whole row like this: any suggestions? thank you!

{1: 0.39085439023582913, 2: 0.7138416909634645, 3: 0.9871959077954673}
helloworld
  • 181
  • 3
  • 12
  • possible duplicate https://stackoverflow.com/questions/3282823/get-the-key-corresponding-to-the-minimum-value-within-a-dictionary – J. Doe Feb 22 '18 at 17:01

3 Answers3

3

If you want the min for each dict in the list, you can use the following list comprehension:

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

Which for your example returns:

[(1, 0.39085439023582913)]

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

If you always have your data in the form of a list with one dictionary, you could also call .items() on the first element of queue and find the min:

print(min(queue[0].items(), key=lambda x:x[1]))
#(1, 0.39085439023582913)
pault
  • 41,343
  • 15
  • 107
  • 149
0

Yes, min(queue) will find minimum in the list and not in the enclosed dictionary Do this:

key_of_min_val = min(queue[0], key=queue[0].get)
print((key_of_min_val , queue[0][key_of_min_val]))
Sagar B Hathwar
  • 536
  • 6
  • 18
0

you can do it through

mykey = min(queue[0], key=queue[0].get)

then just use this key and get your dictionary value

mykey, queue[0][mykey]
J. Doe
  • 3,458
  • 2
  • 24
  • 42