Last Updated on June 17, 2021 by Roshan Parihar
In this tutorial, learn how to get key with a maximum value in Dictionary using Python. The short answer is to use the Python max()
function to find a key with a maximum value in Dictionary.
Each key of the Dictionary may contain elements with numeric values. The elements are not arranged in sequence to find the maximum value. However, you can easily find the key which contains the maximum value.
Here is the method you can use to get the required key in Dictionary. Dictionary contains the elements in such a manner that. Each element contains the key to associated values. If you want to learn more about the dictionary, you may like to read Python Dictionary. So, let’s start the method with examples.
How to Get Key With Maximum Value in Dictionary Using Python
If you want to find the key that contains the largest value, you have to use the max()
function of Python. The function requires two arguments to pass.
The first argument contains the dictionary variable from where you find the key. The second argument contains the method to get key using key=myDict.get
. Where ‘myDict’ is the dictionary variable in the example.
1 2 3 |
myDict = {'one': 24, 'two': 13, 'three': 54, 'four': 9} MaxDictVal = max(myDict, key=myDict.get) print(MaxDictVal) |
Output
The above example contains the Dictionary which contains four elements. Each element contains numeric values. The output contains the key which contains the largest value in the Dictionary.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
I hope you like this post about getting the key that contains the max value.
Reference
Stackoverflow Discussion