简体   繁体   中英

Return the dictionary key linked with max value in the second element of its tuple

I have a dictionary that has this kind of structure:

{0:(text_0, 3), 1:(text_1, 7, 2:(text_2, 1), 3:(text_3, 5)}

I am creating a function that will return the key who's value in the second of element of the tuple is the largest but I can't find a way to make it work. After many attempts this is probably the closest I've gotten:

def maxvalue(dictionary):
    return max(dictionary, key=dictionary.get)

but when I do that I get 3 instead of 1 and can't find a way to tweak it for it to work as I want it to work.

PS: First time posting. Hope the question is formatted correctly.

I don't know if there is a way to do that using a single expression since you need to get the keys from the values.

You need to first get the dictionary value corresponding to the maximum value of the second element in the tuple which you can get with the max() function with a key as you have already tried.

Once the value is obtained, you can iterate over the key-value pairs to get the key matching the dictionary.

Here is the complete code:

d = {0:('text_0', 3), 1:('text_1', 7), 2:('text_2', 1), 3:('text_3', 5)}

max_val = max(d.values(), key=lambda x: x[1]) # get the maximum value tuple
max_key = next(k for k, v in d.items() if v == max_val) # get the key matching the dictionary

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