Python | Get key with maximum value in Dictionary
Last Updated :
23 Feb, 2023
Given a dictionary, the task is to find the key having the maximum value.
Examples :
Input: {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88}
Output: Jaguar
Input: {'Geeks':1900, 'for':1292, 'geek' : 88}
Output: Geeks
Method #1: Using max() function
Python3
Tv = { 'BreakingBad' : 100 , 'GameOfThrones' : 1292 , 'TMKUC' : 88 }
Keymax = max ( zip (Tv.values(), Tv.keys()))[ 1 ]
print (Keymax)
|
Time complexity: O(n log n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(1), as we are not using any extra data structure to store the key with maximum value.
Method 2: Using max() with lambda function
Python3
Tv = { 'BreakingBad' : 100 , 'GameOfThrones' : 1292 , 'TMKUC' : 88 }
Keymax = max (Tv, key = lambda x: Tv[x])
print (Keymax)
|
Time complexity: O(n log n), where n is the number of keys in the dictionary.
Auxiliary space: O(1), as the code only uses a constant amount of extra space to store the maximum key.
Method 3: Using operator
Python3
import operator
Car = { 'Audi' : 100 , 'BMW' : 1292 , 'Jaguar' : 210000 , 'Hyundai' : 88 }
keyMax = max (Car.items(), key = operator.itemgetter( 1 ))[ 0 ]
print (keyMax)
|
Time complexity: O(nlogn), where n is the number of items in the dictionary.
Auxiliary space: O(1), as the space used is constant and does not depend on the size of the input dictionary.
Method 4:
Python3
Company = { 'GFG' : 10000 , 'Hashd' : 2292 , 'Infy' : 200 }
v = list (Company.values())
k = list (Company.keys())
print (k[v.index( max (v))])
|
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), since two lists (v and k) are created of size n.
Method 5: Using iteration:
Here is an additional approach that you could use to find the key with the maximum value in a dictionary:
- Initialize a variable max_key to the first key in the dictionary.
- Iterate over the keys in the dictionary using a for loop.
- For each key, check if the value of the key is greater than the value of the current max_key. If it is, update max_key to be the current key.
- After the for loop has completed, max_key will contain the key with the maximum value in the dictionary.
Implementation:
Python3
d = { 'a' : 10 , 'b' : 20 , 'c' : 30 , 'd' : 40 , 'e' : 50 }
max_key = next ( iter (d))
for key in d:
if d[key] > d[max_key]:
max_key = key
print (max_key)
|
Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...