themacco
themacco

Reputation: 751

Find maximum value in dictionary of lists

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.

Upvotes: 2

Views: 4942

Answers (4)

higrm
higrm

Reputation: 25

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.

Upvotes: 0

Rahul K P
Rahul K P

Reputation: 16081

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

Upvotes: 0

Eduard
Eduard

Reputation: 666

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

Upvotes: 3

Moses Koledoye
Moses Koledoye

Reputation: 78554

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

m = max(i for v in data.values() for i in v)

Upvotes: 5

Related Questions