Get the key corresponding to the maximum value of the dictionary in Python

        Origin: The last exam needed to use pands to return the element with the most occurrences in a column (that is, return the index corresponding to the maximum value in the series structure after the value_counts() counts the number) , so I have recently added pandas knowledge by the way.

Insert picture description here
        So record the method of obtaining the key corresponding to the maximum value in the dictionary

        The following uses dict instead of the dictionary name

Method 1

max(dict,key=dict.get)
min(dict,key=dict.get)

        Students who are not familiar with max() and min() may not understand well, let me explain

        Pass the get() method as a parameter to the max function, then the max function 元素compares the corresponding values. Note: The elements mentioned here are the keys of dict, because when dict is passed into the max function as an iterable object, then the keys of the dictionary will be compared, which is equivalent to passing in dict.keys()

        So it is equivalent to comparing 键1, 键2, ... , 键n, these are iterable objects, what criteria are used to compare these objects?

        Use dict.get('键1'), dict.get('键2'), ... , dict.get('键n'), as a comparison thing (more accurate should be used key('键1'), key('键2'), ... , key('键n')), there are bigger and smaller, what to choose, the maximum is determined by max

       
       

Method 2

min(dict, key=lambda k: dict[k])   
max(dict, key=lambda k: dict[k])   

        I don’t need to explain this, it’s easy to understand

Guess you like

Origin blog.csdn.net/qq_43657442/article/details/109075004