![]() |
VOOZH | about |
Given a dictionary, our task is to find the key having the maximum value. For Example: We are given a dictionary d = {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88} then the output will be Jaguar as it is the key with maximum value in dictionary.
In this method we will use the built-in max() function to identify the key with the highest value in the dictionary and by specifying key=d.get we can ensure that the comparison is based on the dictionary values rather than the keys.
Jaguar
Explanation: max() function is used to find the maximum element where key=d.get ensures the comparison is made based on the values (not keys).
We use the sorted() function to sort the dictionary by its values in descending order and then pick the first key from the sorted list which will correspond to the maximum value.
Jaguar
Explanation: sorted() function sorts the dictionary keys based on their values using key=d.get and setting reverse=True to sort in descending order and the first key in the sorted list is the one with the highest value.
We iterate through each key-value pair in the dictionary comparing the value of each pair with the current maximum value. The key with the highest value is stored and returned at the end of the loop.
Jaguar
Explanation:
We use the max() function with a lambda function to access the dictionary values, this allows us to find the key associated with the maximum value.
Jaguar
Explanation:
Related Articles: