Reputation: 41
I'm trying to get maximum value key
from a list with each element of list is a dictionary like
li = [{'a': 100}, {'b': 200}, {'c': 50}]
Is it possible to get maximum value key
without sorting list? Please help me to solve this.
Upvotes: 1
Views: 113
Reputation: 164
You can get the maximum value in linear time by accessing each element and saving the current maximum value. Edit
People already wrote the pythonic way of doing it. The non pythonic way would be to write a normal loop like this:
li = [{'a': 100}, {'b': 200}, {'c': 50}]
# if you know that all numbers are positive then just use max = 0
max = list(li[0].values())[0]
for values in li:
for value in values.values():
if value > max:
max = value
Upvotes: 1
Reputation: 46849
this would also allow for more items in your dictionaries:
from itertools import chain
from operator import itemgetter
li = [{'a': 100}, {'b': 200}, {'c': 50}]
m = max(chain.from_iterable(item.items() for item in li), key=itemgetter(1))[0]
print(m)
i.e. it would also work if your list looked like this:
li = [{'a': 100}, {'b': 200, 'd': 50}, {'c': 50, 'e': 300, 'f': 20}]
you'd need to take edge-cases like
li = [{'a': 100}, {'b': 100}]
into account. should the answer be a
or b
?
Upvotes: 1
Reputation: 25895
The max
built-in accepts a key
parameter which can be as complex as you want it:
max(li,key=lambda x: list(x.values())[0])
If all your dictionaries have one item, then just get all the values, and retrieve the first (and only) index. Note in Python 2 values()
returns a view
, so you have to convert it to a list before accessing it.
Upvotes: 1