Find key with maximal value in dictionary
Getting the key with maximal value in dictionary is a pretty common task in many programs. Let;s consider simple example.
data = {'a':100, 'b':300, 'c': 200, 'd': 400}
It is necessary to find key with maximal value in the given dictionary ‘data’. Visual inspection give simple answer – it is ‘d’, but how to make it in the python? Here you can find few different solutions
Simplest way to find key with maximal value
data = {'a':100, 'b':300, 'c': 200, 'd': 400}
key = max(data, key=data.get)
print(key) # d
This is simplest solution and it will only find one key, even if few keys have the same maximal value.
Using ‘operator’ library
key = max(data.items(), key=operator.itemgetter(1))[0]
This should be a bit faster way to find the resulting key.
Fastest way to find key for maximal value
In the case of large data is is necessary to use fastest solution, which can help you to avoid unnecessary delays
v=list(data.values())
k=list(data.keys())
key = k[v.index(max(v))]
This is a bit complicated code and it is better to organise it as a function.
Published: 2022-03-15 21:05:13
Updated: 2022-05-04 07:34:15