Find maximum value in dictionary of lists

Question:

How do I find the maximum value of the lists in a dictionary of lists without using a loop? My dictionary looks like:

data = {'key1': list1, 'key2': list2, ... 'keyn': listn}

if I use:

m = max(data.iterkeys(), key=lambda k: data[k])

the output is:

m = 'keyn'

which I don’t want to have.

Asked By: themacco

||

Answers:

Iterate through the items in each list in a generator expression:

m = max(i for v in data.values() for i in v)
Answered By: Moses Koledoye
myDict = {'key1': [1,2,3], 'key2': [4,5,6]}
maxValue = max((max(myDict[key]) for key in myDict))

output: 6

if your new to python, here is a much readable way of how Moses Koledoye did it:

for v in myDict.values():
    for i in v:
        m = i if i > m else m
Answered By: Eduard

You can find the maximum value like this. With out using any loop.

max(max(data.values()))

But this answer is valid when the all values are iterable.

In [1]: myDict = {'key1': [1,2,3], 'key2': [4,5,6]}
In [2]: max(max(myDict.values()))
Out[1]: 6
Answered By: Rahul K P

The two answers which use the max(max(dict.values())) approach do not provide the right answer for a more generic dictionary. They only work if the max value is in the list which has the maximum first value of all the lists.

The code below does not give 65 as the answer, but 53, which is the maximum of the list that has the maximum first value of all lists:

myDict = {'key1': [51,52,53], 'key2': [4,5,65]}
print(max(max(myDict.values())))

Instead, use this:

print(max(max(myDict.values(), key=lambda x: max(x))))

This approach does the following:

  1. Find the list value that has the maximum value — max(myDict.values(), key=lambda x: max(x))
  2. Find the maximum value of that list — the outer call to max()

This has the downside of iterating through the maximum value-containing list twice, so keep that in mind if you are operating on large lists.

Answered By: higrm
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.