Issue
I need to figure out which key has the highest value. The only way I can think of doing that is making a list of values and finding max value from the list to get the highest value. But how do I correlate that value to the key in the dictionary?
d = {}
for i in range(len(names)):
d[i] = len(names[i])
a = max(d.values())
I need to get keys from the values.
Solution
You can use the max
function with a custom key argument:
my_dict = {'a': 10, 'b': 5, 'c': 20, 'd': 15}
max_key = max(my_dict, key=my_dict.get)
print("Key with the highest value:", max_key)
If you dont want to use any inbuilt function like max
Refer the below example :
my_dict = {'a': 10, 'b': 5, 'c': 20, 'd': 15}
max_key = None
max_value = float('-inf')
for key, value in my_dict.items():
if value > max_value:
max_value = value
max_key = key
print("Key with the highest value:", max_key)
Answered By - Selaka Nanayakkara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.