Get Maximum/Minimum Values and Keys in Python Dictionaries
This article explains how to get the maximum and minimum values and their corresponding keys of a dictionary (dict
) in Python.
Get the maximum/minimum key of a dictionary
By passing a dictionary object to the max()
and min
functions, which return the maximum and minimum elements of an iterable object, you get the maximum and minimum keys. This is because dictionaries iterate through their keys.
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
print(max(d))
# e
print(min(d))
# a
Note that strings are compared in alphabetical order.
Get the maximum/minimum value of a dictionary
The values()
method of a dictionary returns a view of its values.
By passing this to the max()
and min
functions, you can retrieve the maximum and minimum values of the dictionary.
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
print(max(d.values()))
# 100
print(min(d.values()))
# 20
Get the key with the maximum/minimum value in a dictionary
You can obtain the key with the maximum/minimum values in a dictionary as follows:
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
print(max(d, key=d.get))
# a
print(min(d, key=d.get))
# b
The key
argument of the max()
and min()
functions specifies a callable object (e.g., a function) to be applied to each element of the iterable before comparison.
In this case, the get()
method of the original dictionary object is specified as the key
argument. The get()
method returns the value for the given key.
Since dictionaries iterate through their keys, applying the get()
method to these keys retrieves their corresponding values. These values are then used to determine the maximum and minimum.
Get the key-value pair with the maximum/minimum value in a dictionary
To obtain both the key and value with the maximum and minimum value in a dictionary, use the items()
method, which returns a view of the dictionary's key-value tuples (key, value)
.
By specifying a lambda expression that retrieves the second element of the tuple (i.e., value) as the key
argument for max()
and min()
functions, the maximum and minimum values are calculated based on the values.
For more information on lambda expressions, refer to the following article:
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
print(max(d.items(), key=lambda x: x[1]))
# ('a', 100)
print(min(d.items(), key=lambda x: x[1]))
# ('b', 20)
You can also use tuple unpacking to assign the key and value to separate variables.
max_k, max_v = max(d.items(), key=lambda x: x[1])
print(max_k)
# a
print(max_v)
# 100
Alternatively, you can use the itemgetter()
function from the standard library operator
instead of a lambda expression. Refer to the following article:
Handle cases when there are multiple maximum/minimum values
In the previous examples, if there are multiple maximum or minimum values, only one of the key or key-value tuple is returned.
Using list comprehension, you can obtain a list of the keys or key-value tuples if there are multiple maximum or minimum values.
Here is an example of obtaining key-value tuples.
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
print([kv for kv in d.items() if kv[1] == max(d.values())])
# [('a', 100), ('d', 100)]
Here is an example of obtaining only the keys as a list.
print([kv[0] for kv in d.items() if kv[1] == max(d.values())])
# ['a', 'd']
With this method, you can obtain a list with one element even if there is only one maximum or minimum value.
print([kv for kv in d.items() if kv[1] == min(d.values())])
# [('b', 20)]
Use pandas.Series
You can also convert the dictionary to a pandas.Series
and process it.
Passing a dictionary to the pandas.Series()
constructor creates a pandas.Series
with the keys as index
and the values as values
.
import pandas as pd
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(s)
# a 100
# b 20
# c 50
# d 100
# e 80
# dtype: int64
print(s.index)
# Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print(s.values)
# [100 20 50 100 80]
Get the maximum/minimum value of a dictionary
You can find the maximum and minimum value of the original dictionary using the max()
and min()
methods of the pandas.Series
.
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(s.max())
# 100
print(s.min())
# 20
Get the maximum/minimum key of a dictionary
The maximum and minimum values of the index
of a pandas.Series
correspond to the maximum and minimum key of the original dictionary.
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(max(s.index))
# e
print(min(s.index))
# a
Get the key with the maximum and minimum value in a dictionary
You can find the key with the maximum and minimum values of the original dictionary using the idxmax()
and idxmin()
methods of the pandas.Series
. If there are multiple maximum or minimum values, only the first key is returned.
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(s.idxmax())
# a
print(s.idxmin())
# b
To obtain all the keys when there are multiple maximum or minimum values, extract the elements equal to the maximum or minimum values using boolean indexing and get the index
attribute.
print(s[s == s.max()])
# a 100
# d 100
# dtype: int64
print(s[s == s.max()].index)
# Index(['a', 'd'], dtype='object')
To convert the index to a list, you can use either the tolist()
method or the list()
function.
print(s[s == s.max()].index.tolist())
# ['a', 'd']
print(list(s[s == s.max()].index))
# ['a', 'd']
The same applies to the minimum value.
In this case, even if there is only one corresponding key, it is returned as an Index
or a list.
print(s[s == s.min()])
# b 20
# dtype: int64
print(s[s == s.min()].index)
# Index(['b'], dtype='object')
print(s[s == s.min()].index.tolist())
# ['b']
print(list(s[s == s.min()].index))
# ['b']
Other processing
By converting a dictionary to a pandas.Series
, you can easily and conveniently perform other operations such as sorting and conditional extraction.
- pandas: Sort DataFrame, Series with sort_values(), sort_index()
- pandas: Select rows with multiple conditions
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(s.sort_values())
# b 20
# c 50
# e 80
# a 100
# d 100
# dtype: int64
print(s[s > 60])
# a 100
# d 100
# e 80
# dtype: int64