4

I have a dictionary mapping an id_ to a list of data values like so: dic = {id_ : [v1, v2, v3, v4]}. I'm trying to iterate through every value in the dictionary and retrieve the max/min of a certain index of the list mappings.

What I want to do is something like this:

maximum = max([data[0], ??) for id_, data in self.dic.items()])

...but obviously this will not work. Is it possible to do this in one line as above?

Clev3r
  • 1,568
  • 1
  • 15
  • 28

2 Answers2

9

You need to use it something like this:

maximum = max(data[0] for data in dic.values())

since you are not using your keys, simply use dict.values() to get just the values.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Will this iterate through every value of index 0 in the dict and return the max? I don't see how. `dic.values()` will return a list of lists `[[1,2,3],[4,5,6]]` – Clev3r Feb 14 '13 at 21:37
  • @Clever. dict.values() returns a list of all the values in the dict. You can try printing out it and see what you get. And yes this will give maimum of data[0] out of all values. – Rohit Jain Feb 14 '13 at 21:38
  • Hm, doesn't seem to be working. Printing out the .values() does return a list of lists, but the maximum is certainly higher than my output. Just glazing over it I can see a val[0] at 70,000 wheras the max is returning 9936. – Clev3r Feb 14 '13 at 21:40
  • @Clever: do your values happen to be strings and not integers or floats? – DSM Feb 14 '13 at 21:41
  • @Clever. What input are you giving? – Rohit Jain Feb 14 '13 at 21:41
  • I'm a class-A dumbass. Maybe I should take a break for the rest of the day. – Clev3r Feb 14 '13 at 21:41
  • @Clever. So you found the issue? And what was it? – Rohit Jain Feb 14 '13 at 21:42
  • I'm scanning a website and reading the strings into a dictionary. I failed to convert the data into floats after `data = line.split()` – Clev3r Feb 14 '13 at 21:43
  • @Clever. Ok. Well, it happens sometimes. – Rohit Jain Feb 14 '13 at 21:45
  • is there a way to get the key of the maximum value in the list? – Mehdi Selbi Aug 31 '21 at 11:38
1

Using a generator expression and max():

In [10]: index = 0

In [11]: dictA = { 1 : [22, 31, 14], 2 : [9, 4, 3], 3 : [77, 15, 23]}

In [12]: max(l[index] for l in dictA.itervalues())
Out[12]: 77

Note: itervalues() returns an iterator over the dictionary’s values without making a copy, and is therefore more efficient than values() (in Python < 3).

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • Is there a significant difference between .itervalues() and .values()? Would it be that .values() returns an entire list while .itervalues() is more conservative with space? – Clev3r Feb 14 '13 at 21:47
  • 1
    @Clever: I was updating my answer while you typed that with an explanation. – johnsyweb Feb 14 '13 at 21:48