简体   繁体   中英

getting minimum (key, value) in a list that holds a dictionary

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}

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)

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]))

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM