Reputation: 1588
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?
Upvotes: 4
Views: 8959
Reputation: 141860
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).
Upvotes: 1
Reputation: 213311
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.
Upvotes: 9