I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:
def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v = list(d.values())
k = list(d.keys())
return k[v.index(max(v))]
To give you an idea, here are some candidate methods:
def f1():
v = list(d1.values())
k = list(d1.keys())
return k[v.index(max(v))]
def f2():
d3 = {v: k for k,v in d1.items()}
return d3[max(d3)]
def f3():
return list(filter(lambda t: t[1] == max(d1.values()), d1.items()))[0][0]
def f3b():
# same as f3 but remove the call to max from the lambda
m = max(d1.values())
return list(filter(lambda t: t[1] == m, d1.items()))[0][0]
def f4():
return [k for k, v in d1.items() if v == max(d1.values())][0]
def f4b():
# same as f4 but remove the max from the comprehension
m = max(d1.values())
return [k for k,v in d1.items() if v == m][0]
def f5():
return max(d1.items(), key=operator.itemgetter(1))[0]
def f6():
return max(d1, key=d1.get)
def f7():
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v = list(d1.values())
return list(d1.keys())[v.index(max(v))]
def f8():
return max(d1, key=lambda k: d1[k])
tl = [f1, f2, f3b, f4b, f5, f6, f7, f8, f4, f3]
cmpthese.cmpthese(tl, c=100)
The test dictionary:
d1 = {1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15,
12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8,
21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19,
30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22,
39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12,
49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33,
58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28,
68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23,
78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31,
88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35,
98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63,
2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21,
124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16,
142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11,
161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32,
182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89,
208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84,
238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30,
263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118,
296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25,
55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108,
377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103,
1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23,
6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119,
592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41,
700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78,
1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99,
976: 24, 166: 112}
And the test results under Python 3.2:
rate/sec f4 f3 f3b f8 f5 f2 f4b f6 f7 f1
f4 454 -- -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0%
f3 466 2.6% -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0%
f3b 14,715 3138.9% 3057.4% -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4%
f8 18,070 3877.3% 3777.3% 22.8% -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2%
f5 33,091 7183.7% 7000.5% 124.9% 83.1% -- -1.0% -2.0% -6.3% -18.6% -29.0%
f2 33,423 7256.8% 7071.8% 127.1% 85.0% 1.0% -- -1.0% -5.3% -17.7% -28.3%
f4b 33,762 7331.4% 7144.6% 129.4% 86.8% 2.0% 1.0% -- -4.4% -16.9% -27.5%
f6 35,300 7669.8% 7474.4% 139.9% 95.4% 6.7% 5.6% 4.6% -- -13.1% -24.2%
f7 40,631 8843.2% 8618.3% 176.1% 124.9% 22.8% 21.6% 20.3% 15.1% -- -12.8%
f1 46,598 10156.7% 9898.8% 216.7% 157.9% 40.8% 39.4% 38.0% 32.0% 14.7% --
And under Python 2.7:
rate/sec f3 f4 f8 f3b f6 f5 f2 f4b f7 f1
f3 384 -- -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2%
f4 394 2.6% -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1%
f8 13,079 3303.3% 3216.1% -- -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2%
f3b 13,852 3504.5% 3412.1% 5.9% -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5%
f6 18,325 4668.4% 4546.2% 40.1% 32.3% -- -1.8% -5.9% -13.5% -29.5% -59.6%
f5 18,664 4756.5% 4632.0% 42.7% 34.7% 1.8% -- -4.1% -11.9% -28.2% -58.8%
f2 19,470 4966.4% 4836.5% 48.9% 40.6% 6.2% 4.3% -- -8.1% -25.1% -57.1%
f4b 21,187 5413.0% 5271.7% 62.0% 52.9% 15.6% 13.5% 8.8% -- -18.5% -53.3%
f7 26,002 6665.8% 6492.4% 98.8% 87.7% 41.9% 39.3% 33.5% 22.7% -- -42.7%
f1 45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1% 74.4% --
You can see that f1
is the fastest under Python 3.2 and 2.7 (or, more completely, keywithmaxval
at the top of this post)
Вступление
В этом руководстве мы рассмотрим, как найти максимальный элемент нескольких распространенных структур данных в Python, таких как список, словарь и кортеж.
Метод max(), встроенный в пространство имен Python, творит чудеса для встроенных типов.
Как получить максимальный элемент списка Python
Список – это встроенный тип Python, который используется для последовательного хранения нескольких ссылок в одном объекте в памяти.
По сравнению с другими языками программирования, список Python по сути представляет собой простой массив. Элементы индексируются на основе их положения в списке, и может быть несколько элементов с одинаковым значением.
Основное отличие в том, что списки в Python могут содержать элементы разных типов. Они разнородны.
# List of different type elements
example_list = ["string", 5, "five", 4, "4"]
Примечание: если элементы не сопоставимы с помощью операторов сравнения (<,>,==,!=), функция max() не будет работать. Таким образом, мы убедимся, что список однороден, прежде чем пытаться найти максимальный элемент.
Пока вы правильно сравниваете элементы, вы можете найти максимальный элемент независимо от типа. Большую часть времени вы будете работать с целыми числами:
integer_list = [24, 9, 20, 17, 201, 16, 7]
Самый простой способ получить максимальный элемент списка – использовать встроенный метод max():
max_element = max(integer_list)
print("Max element of a list: ", max_element)
Ожидаемый результат:
Max element: 201
Вы можете сравнить строки лексикографически и найти лексикографически наибольшую строку в списке с помощью функции max():
string_list = ["string", "five", "4"]
max_element = max(string_list)
print("Max element:", max_element)
Результат:
Max element: string
Другой способ найти максимальный элемент списка – отсортировать его с помощью метода sort(), а затем получить последний элемент отсортированного списка, поскольку метод sort() сортирует список в порядке возрастания:
integer_list = [24, 9, 20, 17, 201, 16, 7]
integer_list.sort()
# myList = [7, 9, 16, 17, 20, 24, 201]
max_element = integer_list[-1]
print("Max element of a list: ", max_element)
Этот код также будет иметь тот же результат:
Max element of a list: 201
Если мы также хотим найти индекс элемента max, самый простой способ – использовать встроенный метод index():
integer_list = [24, 9, 20, 17, 201, 16, 7]
max_element = max(integer_list)
max_element_index = integer_list.index(max_element)
print("Max element of a list: ", max_element, " at index: ", max_element_index)
Результат:
Max element of a list: 201 at index: 4
Как получить максимальный элемент словаря Python
Словари в Python используются для хранения пар ключ-значение. Пары с одним и тем же ключом не допускаются, и, начиная с Python 3.7, пары в словаре считаются упорядоченными.
Словари определяются списком пар key-value между парой фигурных скобок:
dictionary = {
"key24": 24,
"key7": 9,
"key20": 201,
"key17": 17,
"key201": 201,
}
Самый простой способ получить значение элемента max словаря также заключается в использовании встроенного метода max() со списком значений, передаваемых в качестве аргумента:
max_element = max(dictionary.values())
print("Max element of a dict: ", max_element)
Всё сводится к предыдущему методу, поскольку values() возвращает значения, хранящиеся в списке. Это даст правильный результат:
Max element of a dict: 201
Если вы хотите найти ключ первого элемента с максимальным значением, самый простой способ – использовать метод max(), предоставляющий словарь и извлекающий элемент через dictionary.get().
max_val = max(dictionary.values())
max_val_key = max(dictionary, key=dictionary.get)
print("Max element of a dict:", max_val, "with the key:", max_val_key)
Так мы выведем значение элемента max и первого соответствующего ключа:
Max element of a dict: 201 with the key: key20
Примечание: у вас может возникнуть соблазн использовать max(dictionary), чтобы найти ключ с максимальным значением. Однако так вы вернёте сам максимальный ключ. В нашем случае программа вернула бы ключ с максимальным лексикографическим значением в словаре.
Как получить максимальный элемент кортежа
Кортеж – это встроенный тип Python, последовательно хранящий ссылки на несколько объектов в памяти. Они во многом похожи на списки. Различие лишь в том, что кортеж – это неизменяемая структура данных, в отличие от списка.
Обычно они используются для хранения только нескольких результатов, в виде типов возвращаемых функций.
В Python мы описываем кортежи с помощью пары скобок:
# Tuple of different element types
exampleTuple = ("string", 5, "five", 4, "4")
Вы можете запускать метод max() только для совместимых типов данных:
int_tuple = (24, 9, 20, 17, 201, 16, 7)
string_tuple = ('one', 'two', 'three')
Вероятно, самый простой способ получить максимальный элемент кортежа – использовать встроенный метод max():
int_tuple = (24, 9, 20, 17, 201, 16, 7)
string_tuple = ('one', 'two', 'three')
max_int = max(int_tuple)
print("Max element of a tuple: ", max_int)
max_str = max(string_tuple)
print("Max element of a tuple: ", max_str)
Опять-таки, это приводит к наибольшему целому числу и лексикографически наибольшей строке:
Max element of a tuple: 201
Max element of a tuple: two
Заключение
Поиск максимального элемента структуры данных – довольно распространенная задача. Все стандартные структуры данных в Python имеют аналогичный способ поиска элемента max – полагаясь на метод max() во всех случаях.
В этом руководстве мы рассмотрели, как найти максимальный элемент нескольких наиболее популярных структур данных в Python, принимая во внимание особенности каждой из них.
Просмотры: 9 206
In this Python tutorial, we will discuss the Python find max value in a dictionary.
To obtain the maximum value from the dictionary, use the in-built max() function of Python.
Here we will discuss the following 3 methods
- Using dict.items()
- Using max() and lambda function
- Using max() and dict()
In this Python section, we are going to discuss different methods for finding the max value in a dictionary.
Method-1: Using dict.items()
Here we will know how to find the maximum value in a dictionary using the dict.items() method:
# Import the operator module
import operator
# Create a dictionary with some key-value pairs
max_dict = {'Australia':178, 'Germany':213, 'Japan': 867}
# Use the operator.itemgetter() method in combination with the max() function to find the key with the maximum value
new_ma_val = max(max_dict.items(), key=operator.itemgetter(1))[0]
# Print the key with the maximum value
print((new_ma_val))
In the above code, we first import the operator module, which provides functions for working with operator overloading.
- Then we create a dictionary max_dict with key-value pairs. We use the operator.itemgetter() method in combination with the max() function to find the key with the maximum value.
- The operator.itemgetter() method is used to extract the value from the tuple by using the index passed to it, which is 1 in this case. The max() function compares the values and returns the key-value pair that has the maximum value.
- The key is extracted from the returned tuple by using [0] indexing and is assigned to the variable new_ma_val. Finally, we print the key with the maximum value which is “Japan” with 867 as the max value.
Method-2: Using max() and lambda function
Here we will know how to find the maximum value in a dictionary using the max() and lambda methods:
# Create a dictionary with some key-value pairs
Country_dict = {'China':982, 'Egypt':758, 'Malaysia' : 12}
# Use the max function with a lambda function to find the key with the maximum value
new_val = max(Country_dict, key= lambda x: Country_dict[x])
# Print the key with the maximum value
print("maximum value from dictionary:",new_val)
In the above code, we first create a dictionary Country_dict with key-value pairs.
- Then we use the max() function with a lambda function to find the key with the maximum value. The lambda function takes a single argument x which is the key of the dictionary and returns the value associated with the key.
- The max() function then compares the values and returns the key that has the maximum value. Finally, we print the key with the maximum value, which is ‘China’ with 982 as the max value in this case.
Method-3: Using max() and dict()
Here we will know how to find the maximum value in a dictionary using the max() and dict() methods:
# Create a dictionary with some key-value pairs
name_dict = {"Oliva": 18, "potter": 56, "Harry": 15}
# Extract the values from the dictionary and assign it to a variable
new_val = name_dict.values()
# Use the max function to find the maximum value
maximum_val = max(new_val)
# Print the maximum value
print("Maximum value from dict:",maximum_val)
In the above code, we first create a dictionary name_dict with key-value pairs.
- Then we extract the values from the dictionary using the .values() method and assign them to a variable new_val.
- We then use the max() function to find the maximum value from the extracted values. Finally, we print the maximum value which is 56 in this case.
Read: How to create an empty Python dictionary
Python find max value in a nested dictionary
In this Python section, we will learn how to find the max value in a dictionary within the dictionary.
# Create a nested dictionary
my_dictionary = {'Micheal' : {'i' : 15, 'z' : 14},
'George' : {'q' : 2, 'y' : 10, 'w' : 3},
'John' : {'n' : 19}}
# Create a empty dictionary to store the result
new_out = {}
# Iterate over the outer dictionary keys and values
for new_k, new_v in my_dictionary.items():
count_new = 0
# Iterate over the inner dictionary values
for element in new_v.values():
# Check if current value is greater than the previous maximum
if element > count_new:
count_new = element
# Assign the maximum value to the outer dictionary key
new_out[new_k] = count_new
# Print the final dictionary with maximum values
print(new_out)
In the above code, we first create a nested dictionary my_dictionary with multiple keys, each key having its own dictionary as a value.
- We then create an empty dictionary new_out to store the result. We use a for loop to iterate over the outer dictionary keys and values, and another for loop to iterate over the values of the inner dictionary.
- We compare each value of the inner dictionary with a variable count_new, updating the variable if the current value is greater than the previous maximum.
- Then we assign the maximum value to the outer dictionary key by using this key as the key for the new_out dictionary and the maximum value as the value for this key.
Read: Python Dictionary to CSV
Python find max value in a dictionary of lists
In this Python section, we will discuss how to find the max value in a dictionary containing the list.
# Create a dictionary with some key-value pairs
dict_new = {'USA': [17,27,81], 'United Kingdom': [19,61,92]}
# Use max() and list comprehension to find the maximum value in the dictionary
new_val = max((max(dict_new[key]) for key in dict_new))
# Print the maximum value
print(new_val)
In the above code, we first create a dictionary dict_new with key-value pairs.
- Then we use the max() function and list comprehension to find the maximum value in the dictionary.
- The list comprehension iterates over the keys of the dictionary and for each key, it finds the maximum value in the corresponding list using the max() function.
- Finally, we print the maximum value which is 92 in this case.
You may also like to read the following tutorials on Python dictionary:
- Python dictionary pop
- Python dictionary get() method [With Examples]
- Python dictionary Copy
- Python dictionary contains
- Python dictionary multiple keys
In this Python tutorial, we have discussed the Python find max value in a dictionary. Also, we have covered the following methods:
- Using dict.items()
- Using max() and lambda function
- Using max() and dict()
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Are you wondering how to find the minimum and maximum values in a Python dictionary? Here you will find the answers you are looking for.
The easiest way to find the minimum or maximum values in a Python dictionary is to use the min() or max() built-in functions applied to the list returned by the dictionary values() method. You can also pass just the dictionary to the max() or min() functions but in that case you have to use the optional key argument to identify minimum or maximum based on dictionary values and not on keys.
We will go through multiple ways to solve this problem so you can choose the one you prefer.
Let’s start coding!
How Do You Find the Maximum Value in a Python Dictionary?
Let’s assume that we have created a game and that we are storing the points of all players in a dictionary.
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 230}
The first thing I can think about to calculate the maximum value in a dictionary would be to use a Python built-in function.
Python provides a built-in function called max() that returns the largest item in an iterable.
Also, one of the methods provided by Python dictionaries is values() that returns a list of all the values in the dictionary.
>>> print(points.values)
<built-in method values of dict object at 0x7f9448181500>
Firstly let’s call the values() method on our dictionary to see what we get back:
>>> print(points.values())
dict_values([100, 450, 230])
Then try to pass this list to the max function…
>>> print(max(points.values()))
450
We got back what we wanted, the maximum value in the dictionary.
In the next section we will see how to get the maximum value in the dictionary while also keep tracked of the key mapped to that value.
Get Maximum Value and Its Key From a Dictionary in Python
In the previous section we have seen that the Python max function can be used with iterables.
Is a Python dictionary an iterable?
A Python dictionary is an iterable because it has the dunder method called __iter__. To verify all the methods that belong to a dictionary you can use the command dir(dict).
>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Here is what happens if you pass the points dictionary defined in the previous section to the max function:
>>> max(points)
'Kate'
The max function returns the key with maximum value in the dictionary. In this case the keys are compared alphabetically.
This is not what we want considering that we want to get the maximum value in the dictionary and not the maximum dictionary key.
To get the maximum value we have to pass the optional argument key to the max function. The argument key is used to specify a one-argument ordering function.
This is the same approach used with the built-in sorted function.
We pass points.get as the key argument so the max function goes through all the keys in the dictionary and gets the maximum after calling the points.get() method for each key (this method returns the value associated to a given key).
>>> max(points, key=points.get)
'Andy'
Once again…
We are passing points.get to the key argument to get the maximum based on the values in the dictionary and not based on the keys.
This time the max function returns the key ‘Andy’ because it’s the key associated to the highest value in the dictionary (450).
To get the actual value we simply have to retrieve the value mapped to the dictionary key obtained with the previous code:
>>> print(points[max(points, key=points.get)])
450
And if we want to print both key and maximum value we can use the following code…
>>> print("Key associated to the maximum value: {} - Maximum value: {}".format(max(points, key=points.get), points[max(points, key=points.get)]))
Key associated to the maximum value: Kate - Maximum value: 450
To print the previous message we have used the string format method.
How Do You Get All the Keys with the Highest Value in a Dictionary?
In the previous examples there was only one maximum value in the dictionary.
But what happens if in the previous dictionary we have the same maximum value associated to different keys?
Here is what I mean…
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 450}
In this case both Andy and Kate have 450 points and when I use the code created in the previous section, here is the result:
>>> print("Key associated to the maximum value: {} - Maximum value: {}".format(max(points, key=points.get), points[max(points, key=points.get)]))
Key associated to the maximum value: Andy - Maximum value: 450
We only get back the key ‘Andy’ and this is not correct.
How can we get back a dictionary that contains both keys associated to the maximum value? (in this case Andy and Kate).
We can start with the maximum value and then identify the keys whose value matches the maximum value.
To create this new dictionary we will use a dictionary comprehension.
So let’s calculate the maximum value first and store it in the variable max_value:
>>> max_value = max(points.values())
Then use a dictionary comprehension to create the new dictionary by using the keys that match the maximum value.
>>> {key:value for key, value in points.items() if value == max_value}
{'Andy': 450, 'Kate': 450}
To understand the comprehension expression above you have to remember what the dictionary items() method returns.
>>> print(points.items())
dict_items([('Jake', 100), ('Andy', 450), ('Kate', 450)])
Does it makes sense now?
In the dictionary comprehension we go through each tuple in the list and we take key and value from the tuples whose value matches the maximum value.
How to Use the Python Max Function with a Lambda Expression
Let’s go through another way to get the maximum value and the key associated to it from a Python dictionary.
Note: with this approach we are making the assumption that the maximum value in our dictionary can only be one.
Take the following dictionary:
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 200}
We will calculate the maximum tuple in the list returned by points.items().
>>> print(points.items())
dict_items([('Jake', 100), ('Andy', 450), ('Kate', 200)])
Here is the result we get by simply applying the max built-in function to the list of tuples above…
>>> max(points.items())
('Kate', 200)
Hmmm….this is not what we want…
We are getting this tuple back from the max function because the function is returning the maximum tuple using the first element of the tuple as ordering criteria.
If you want to provide a different ordering criteria to the max() function we can pass the optional key argument that allows to specify a one-argument ordering function.
In this case our ordering function will be a lambda that picks the second element in each tuple to identify the maximum tuple.
The second element in a given tuple represents a value in the original dictionary.
The lambda function we will pass is…
lambda data: data[1]
The call to the max function becomes:
>>> max(points.items(), key = lambda data: data[1])
('Andy', 450)
As you can see we are getting back the correct key / value pair from the dictionary based on the fact that 450 is the maximum value.
Using operator.itemgetter() with Max Function to Get the Maximum Value in a Dictionary
There is also another way to write the lambda function we have seen in the previous section:
lambda data: data[1]
This lambda function can be replaced by the operator.itemgetter() function, part of the operator module.
By passing the index 1 to operator.itemgetter() you get back the second item of each tuple in the points.items() list.
>>> import operator
>>> max(points.items(), key = operator.itemgetter(1))
('Andy', 450)
As you can see the itemgetter function is used as key argument to identify the maximum value in the dictionary.
If you only want to get back the maximum value you can retrieve it by accessing index 1 of the tuple returned.
>>> max(points.items(), key = operator.itemgetter(1))[1]
450
Another Way to Find the Maximum Dictionary Value Using a Lambda and the Max Function
Let’s have a look at another way to find the maximum value in a dictionary by using a lambda function together with the max function.
In the previous section we have used the lambda function to identify the maximum second item in each tuple returned by points.items().
This time we will work on the original dictionary points instead of points.items().
We want to define a lambda function that given a key returns the value mapped to that key. Then we will use this lambda as optional key argument (it will be used as ordering function by the max function).
The lambda function will be:
lambda dict_key: points[dict_key]
Given the following dictionary…
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 200}
We can use the max function as shown below:
>>> max_value = max(points, key = lambda dict_key: points[dict_key])
>>> print(max_value)
Andy
Note: in the same way we have seen in the previous section this approach doesn’t work if the same maximum value is assigned to multiple keys.
Note 2: the key argument of the max() function has nothing to do with the dictionary key. To make this clear I have used dict_key in the lambda function.
See this as an exercise to practice the use of dictionaries, lambdas and the max function.
How Do You Find the Minimum Value in a Python Dictionary?
To find the minimum value in a Python dictionary you can use the min() built-in function applied to the result of the dictionary values() method.
This is similar to the approach we have used previously to calculate the maximum value.
Let’s use the following dictionary…
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 450}
And here is the minimum value in the dictionary calculated using the min() function.
>>> min_value = min(points.values())
>>> print(min_value)
100
And now with a dictionary comprehension and an if statement we can create a dictionary that contains all the keys that match the minimum value.
>>> {key:value for key, value in points.items() if value == min_value}
{'Jake': 100}
Let’s confirm it also works if multiple keys are mapped to the minimum value.
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 450, 'Jeremy': 100}
>>> {key:value for key, value in points.items() if value == min_value}
{'Jake': 100, 'Jeremy': 100}
It works!
Find Maximum Value in a Python Dictionary Using an “Inverse” Dictionary
If you think we have gone through enough ways to retrieve the maximum or minimum value in a dictionary, think twice 🙂
I want to show you an alternative approach that is quite different from the ones we have seen so far.
Start from the following dictionary:
>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 230}
Now…
I want to swap keys and values in the dictionary.
You will see why shortly…
The format of the original dictionary is:
{key1: value1, key2: value2, ..., keyN: valueN}
The new dictionary will be:
{value1: key1, value2: key2, ..., valueN: keyN}
Let’s do this first and then you will see how you can use the new dictionary to get the maximum value.
To swap keys and values in the dictionary we can use a dictionary comprehension.
>>> points_swapped = {value:key for key, value in points.items()}
>>> print(points_swapped)
{100: 'Jake', 450: 'Andy', 230: 'Kate'}
Make sure you understand this comprehension before you continue reading.
Now, we can use the max() function with the new dictionary to get the maximum value in the dictionary.
>>> print(max(points_swapped))
450
The same applies to the min() function that returns the minimum value in the dictionary:
>>> print(min(points_swapped))
100
Conclusion
Wow, we have seen lots of different ways to retrieve maximum and minimum values from a Python dictionary.
It has been a great opportunity to review Python concepts like:
- Built-in functions (min / max) with and without the optional key argument.
- Dictionary methods: dict.values() and dict.items().
- Lambda functions.
- The itemgetter function of the Python operator module.
- Dictionary comprehensions.
I hope you have found this article useful.
And now, what else would you like to learn?
Let me know in the comments below 🙂
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
d = {‘apple’:9,’oranges’:3,’grapes’:22}
How do I return the largest key/value?
Edit: How do I make a list that has this sorted by largest to lowest value?
cs95
372k95 gold badges687 silver badges739 bronze badges
asked May 19, 2010 at 21:33
1
>>> d = {'apple':9,'oranges':3,'grapes':22}
>>> v, k = max((v, k) for k, v in d.items())
>>> k
'grapes'
>>> v
22
Edit: To sort them:
>>> items = sorted(((v, k) for k, v in d.items()), reverse=True)
>>> items
[(22, 'grapes'), (9, 'apple'), (3, 'oranges')]
answered May 19, 2010 at 21:40
FogleBirdFogleBird
73.7k25 gold badges124 silver badges131 bronze badges
1
You want to use max(). To get the largest key use:
max(d.keys())
Or:
max(d)
To get the largest value use:
max(d.values())
answered May 19, 2010 at 21:39
Jason WebbJason Webb
7,9189 gold badges40 silver badges49 bronze badges
If you want the key with the highest value from your dictionary then this is the answer.
max(d.keys(), key=d.get)
answered Jan 12, 2020 at 13:06
max(d.values())
Edited:
The above gives you the max value. To get the key/value pair with the max value, you could do this:
sorted(d.items(), key=lambda x:x[1], reverse=True)[0]
answered May 19, 2010 at 21:35
Daniel RosemanDaniel Roseman
585k63 gold badges872 silver badges886 bronze badges
1
“””How do I print the key, too? “””
maxval = max(d.itervalues())
maxkeys = [k for k, v in d.iteritems() if v == maxval]
answered May 19, 2010 at 21:56
John MachinJohn Machin
80.9k11 gold badges140 silver badges187 bronze badges