1

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.

alexandresaiz
  • 2,629
  • 7
  • 27
  • 40
themacco
  • 461
  • 2
  • 6
  • 8

3 Answers3

3

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

m = max(i for v in data.values() for i in v)
Moses Koledoye
  • 74,909
  • 8
  • 119
  • 129
  • Thank you! I knew that there was I way like this but (I'm new to python) I didn't get it – themacco Jul 13 '16 at 08:18
  • @themacco You could catch up with a little reading [Generator Expressions vs. List Comprehension](http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension) – Moses Koledoye Jul 13 '16 at 08:32
3
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
Eduard
  • 634
  • 1
  • 8
  • 24
0

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
Rahul K P
  • 10,793
  • 3
  • 32
  • 47