HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Find the key of the min or max value in a Python dictionary

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
minvaluefindthemaxpythonkeydictionary

Problem

Python's min() and max() functions can be used to find the minimum and maximum values in a dictionary. However, if you want to find the key of the minimum or maximum value, you can use the key parameter of these functions.
You can use min() with the key parameter set to dict.get() to find and return the key of the minimum value in a given dictionary.
Subsequently, you can replace min() with max() to find the key of the maximum value in the dictionary.

Solution

def key_of_min(d):
  return min(d, key = d.get)

key_of_min({'a':4, 'b':0, 'c':13}) # b


Subsequently, you can replace min() with max() to find the key of the maximum value in the dictionary.

Code Snippets

def key_of_min(d):
  return min(d, key = d.get)

key_of_min({'a':4, 'b':0, 'c':13}) # b
def key_of_max(d):
  return max(d, key = d.get)

key_of_max({'a':4, 'b':0, 'c':13}) # c

Context

From 30-seconds-of-code: key-of-min-max

Revisions (0)

No revisions yet.