 # How to Get the Key with Minimum Value in a Python Dictionary?

I have spent my morning hours on an important mission. What is the cleanest, fastest, and most concise answer to the following question: How do you find the key with the minimum value in a Python dictionary?  Most answers on the web say you need to use a library but this is not true!

Simply use the min function with the key argument set to `dict.get`:

```income = {'Anne' : 1111,
'Bert' : 2222,
'Cara' : 9999999}

print(min(income, key=income.get))
# Anne```

The min function goes over all keys, `k`, in the dictionary income and takes the one that has minimum value after applying the `income.get(k)` method. The `get()` method returns the value specified for key, `k`, in the dictionary.

Play with it yourself in our interactive code shell:

Now, read the 4-min article or watch the short video to fully understand this concept.

## What’s the Min Function in Python?

Most likely, you already know Python’s min(…) function. You can use it to find the minimum value of any iterable or any number of values. Here are a few examples using the min function without specifying any optional arguments.

```income = {'Anne' : 1111,
'Bert' : 2222,
'Cara' : 9999999}

print(min(income, key=income.get))
# Anne

# Key that starts with 'smallest' letter of the alphabet
print(min(income))
# Anne

# Smallest value in the dictionary income
print(min(income.values()))
# 1111

# Smallest value in the given list
print(min([1,4,7,5,3,99,3]))
# 1

# Compare lists element-wise, min is first list to have a larger
# element
print(min([1,2,3],[5,6,4]))
# [1, 2, 3]

# Smallest value in the given sequence of numbers
print(min(5,7,99,88,123))
# 5
```

So far so good. The min function is very flexible. It works not only for numbers but also for strings, lists, and any other object you can compare against other objects.

Now, let’s look at the optional arguments of the min function. One of them is `'key'`. Let’s find out what it does.

## How Does the Key Argument of Python’s min() Function Work?

The last examples show the intuitive workings of the min function: you pass one or more iterables as positional arguments.

Intermezzo: What are iterables? An iterable is an object from which you can get an iterator. An iterator is an object on which you can call the next() method. Each time you call next(), you get the ‘next’ element until you’ve got all the elements from the iterator. For example, Python uses iterators in for loops to go over all elements of a list, all characters of a string, or all keys in a dictionary.

When you specify the key argument, define a function that returns a value for each element of the iterable. Then each element is compared based on the return value of this function, not the iterable element (the default behavior).

Here is an example:

```lst = [2, 4, 8, 16]

def inverse(val):
return -val

print(min(lst))
# 2

print(min(lst, key=inverse))
# 16```

We define a function `inverse()` that returns the value multiplied by -1. Now, we print two executions of the `min()` function.

• The first is the default execution: the minimum of the list `[2, 4, 8, 16]` is 2.
• The second uses key. We specify `inverse` as the key function. Python applies this function to all values of `[2, 4, 8, 16]`. It compares these new values with each other and returns the min. Using the inverse function Python does the following mappings:

Python calculates the minimum based on these mappings. In this case, the value 16 (with mapping -16) is the minimum value because -2 > -4 > -8 > -16.

Now let’s come back to the initial question:

## How to Get the Key with the Minimum Value in a Dictionary?

We use the same example as above. The dictionary stores the income of three persons John, Mary, and Alice. Suppose you want to find the person with the smallest income. In other words, what is the key with the minimum value in the dictionary?

Now don’t confuse the dictionary key with the optional key argument of the `min()` function. They have nothing in common – it’s just an unfortunate coincidence that they have the same name!

From the problem, we know the result is a dictionary key. So, we call `min()` on the keys of the dictionary. Note that `min(income.keys())` is the same as `min(income)`.

However, we want to compare dictionary values, not keys. We’ll use the key argument of `min()` to do this. We must pass it a function but which?

To get the value of `'Anne'`, we can use bracket notation – `income['Anne']`. But bracket notation is not a function, so that doesn’t work. Fortunately, `income.get('Anne')` does (almost) the same as `income['Anne']` and it is a function! The only difference is that it returns `None` if they key is not in the dictionary. So we’ll pass that to the key argument of `min()`.

```income = {'Anne' : 1111,
'Bert' : 2222,
'Cara' : 9999999}

print(min(income, key=income.get))
# Anne```

## How to Get the Key with the Maximum Value in a Dictionary?

If you understood the previous code snippet, this one will be easy. To find the key with maximum value in the dictionary, you use the `max()` function.

```income = {'Anne' : 1111,
'Bert' : 2222,
'Cara' : 9999999}

print(max(income, key=income.get))
# Cara```

The only difference is that you use the built-in `max()` function instead of the built-in `min()` function. That’s it.

Related article:

## Find the Key with the Min Value in a Dictionary – Alternative Methods

There are lots of different ways to solve this problem. They are not as beautiful or clean as the above method. But, for completeness, let’s explore some more ways of achieving the same thing.

In a StackOverflow answer, a user compared nine (!) different methods to find the key with the minimum value in a dictionary. Here they are:

```income = {'Anne' : 11111,
'Bert' : 2222,
'Cara' : 9999999}

# Convert to lists and use .index(max())
def f1():
v=list(income.values())
k=list(income.keys())
return k[v.index(min(v))]

# Dictionary comprehension to swap keys and values
def f2():
d3={v:k for k,v in income.items()}
return d3[min(d3)]

# Use filter() and a lambda function
def f3():
return list(filter(lambda t: t==min(income.values()), income.items()))

# Same as f3() but more explicit
def f4():
m=min(income.values())
return list(filter(lambda t: t==m, income.items()))

# List comprehension
def f5():
return [k for k,v in income.items() if v==min(income.values())]

# same as f5 but remove the max from the comprehension
def f6():
m=min(income.values())
return [k for k,v in income.items() if v==m]

def f7():
return min(income,key=income.get)

# Similar to f1() but shortened to 2 lines
def f8():
v=list(income.values())
return list(income.keys())[v.index(min(v))]

# Similar to f7() but use a lambda function
def f9():
return min(income, key=lambda k: income[k])

print(f1())
print(f2())
print(f3())
print(f4())
print(f5())
print(f6())
print(f7())
print(f8())
print(f9())
# Bert (all outputs)
```

In a benchmark performed on a large dictionary by the StackOverflow user, f1() turned out to be the fastest one.

So the second best way to get the key with the minimum value from a dictionary is:

```income = {'Anne' : 11111,
'Bert' : 2222,
'Cara' : 9999999}

v=list(income.values())
k=list(income.keys())
print(k[v.index(min(v))])
# Bert```

## Find Key with Shortest Value in Dictionary

We know how to find the minimum value if the values are numbers. What about if they are lists or strings?

Let’s say we have a dictionary that records the number of days each person worked this month. If they worked a day, we append 1 to that person’s list. If they didn’t work, we don’t do anything.  At the end of the month, our dictionary looks like this.

```days_worked = {'Anne': [1, 1, 1, 1],
'Bert': [1, 1, 1, 1, 1, 1],
'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}```

The total number of days worked each month is the length of each list. If all elements of two lists are the same (as is the case here), they are compared based on their length.

```# Length 2 is less than length 4
>>> [1, 1] < [1, 1, 1, 1]
True```

So we can use the same code we’ve been using in the article to find the key with the minimum value.

```>>> min(days_worked, key=days_worked.get)
'Anne'```

If we update our dictionary so that Bert has worked the most days and apply `min()` again, Python returns `'Anne'`.

```>>> days_worked = {'Anne': [1, 1, 1, 1],
'Bert': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}

# Anne has now worked the least
>>> min(days_worked, key=days_worked.get)```

## Find Key With Min Value in a List of Dictionaries

Let’s say we have 3 dictionaries containing income information. We want to find the key with the min value from all 3 dictionaries.

```income1 = {'Anne': 1111,
'Bert': 2222,
'Cara': 3333}

income2 = {'Dani': 4444,
'Ella': 5555,
'Fred': 6666}

income3 = {'Greg': 7777,
'Hope': 8888,
'Igor': 999999999999}

list_of_dicts = [income1, income2, income3]```

We can see that `'Anne'` has the lowest income so we expect that to be returned.

There are several ways to do this. The simplest is to put all key-value pairs into one dictionary using a for loop. Then we call `min()` as usual.

```# Initialise empty dict
>>> big_dict = {}

# Use for loop and .update() method to add the key-value pairs
>>> for dic in list_of_dicts:
big_dict.update(dic)

# Check the result is as expected
>>> big_dict
{'Anne': 1111,
'Bert': 2222,
'Cara': 3333,
'Dani': 4444,
'Ella': 5555,
'Fred': 6666,
'Greg': 7777,
'Hope': 8888,
'Igor': 999999999999}

# Call min() and specify key argument
>>> min(big_dict, key=big_dict.get)
'Anne' ```

## Where to Go From Here?

Every Python master must know the basics. Improving your basic code understanding skills by 20% will improve your productivity by much more than anything else. Why? Because everything else builds upon the basics.

But most material online is tedious and boring. That’s why I’ve written a new and exciting way of learning Python, while measuring and comparing your skills against other coders. Check out the book “Coffee Break Python”. It’s LeanPub 2019 bestseller in the category Python! 