简体   繁体   中英

Finding key in a dictionary with list as value (Python)

I have a dictionary in the form of:

my_dict = { "a" : ["Hey", 3] , "b" : ["Hello, 2], "c" : ["Heya", 8] }

(and every list is of the same format and "size"). I want to find the key that has the minimum value of each list's second column. In this example, based on the integer values, so the key I'd get is "b". I tried writing this as a list comprehension with lambda function but couldn't get it to work so I ended up with this:

min = 60  # with 60 being a logical maximum value
for key in my_dict:
    if my_dict[key][1] < min:
        min = wordDict[key][1]
        min_key = key
min_key

Is there a more efficient and "elegant" way?

You can use a custom key function in min :

my_dict = { "a":["Hey", 3] , "b":["Hello", 2], "c":["Heya", 8] }
r = min(my_dict, key=lambda x:my_dict[x][-1])

Output:

'b'

without using min function, just for loop. iterate over the dictionary and keep checking the minimum value and corresponding key.

import sys
my_dict = { "a" : ["Hey", 3] , "b" : ["Hello", 2], "c" : ["Heya", 8] }# your code goes here
 
min_val = sys.maxsize
min_val_key = None
 
for i, v in my_dict.items():
    if min_val>v[1]:
        min_val = v[1]
        min_val_key = i
 
print(f"min value is {min_val} and key is {min_val_key}")

output

min value is 2 and key is b

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