Reputation: 181
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}
Upvotes: 3
Views: 4055
Reputation: 3634
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]
Upvotes: 0
Reputation: 43494
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)
Upvotes: 3
Reputation: 536
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]))
Upvotes: 0