AntMau
AntMau

Reputation: 305

Python - Get max value in a list of dict

I have a dataset with this structure :

In[17]: allIndices
Out[17]: 
[{0: 0, 1: 1.4589, 4: 2.4879},
{0: 1.4589, 1: 0, 2: 2.1547},
{1: 2.1547, 2: 0, 3: 4.2114},
{2: 4.2114, 3: 0},
{0: 2.4879, 4: 0}]

I'd like to identify the highest value inside the list of dict. I do as follow :

def findMax(data):

    possiblemax = []
    for i in range(len(data)):
        temp = list(data[i].values())
        tempmax = max(temp)
        possiblemax.append(tempmax)

    maxValue = max(possiblemax)
    return maxValue

It works but I work with a very large dataset and it's a little bit slow. I was wondering of a better and faster way of doing this.

Thanks a lot

Upvotes: 6

Views: 9416

Answers (3)

Alex Taylor
Alex Taylor

Reputation: 8813

I think the one liner version is succinct without being unreadable:

my_list = [{0: 0, 1: 1.4589, 4: 2.4879},
           {0: 1.4589, 1: 0, 2: 2.1547},
           {1: 2.1547, 2: 0, 3: 4.2114},
           {2: 4.2114, 3: 0},
           {0: 2.4879, 4: 0}]
print(max(max(part.values()) for part in my_list))

Python 3 code. Use dict.itervalues() for Python 2.

Upvotes: 4

Asav Patel
Asav Patel

Reputation: 1162

If you only wanted to iterate through the list once, you could try this.

import sys
lo,hi = sys.maxint,-sys.maxint-1

for item in (item.values() for item in allIndices):
    for x in item:
        lo,hi = min(x,lo),max(x,hi)

print hi[0]

Upvotes: 0

Prune
Prune

Reputation: 77837

Iterate over all dictionaries in the list; iterate over each dictionary, grabbing the values. Take max of that. Use the built-in constructors to let the run-time system optimize things for you, as best it can.

In Python 2.7:

ddd = [{0: 0, 1: 1.4589, 4: 2.4879},
       {0: 1.4589, 1: 0, 2: 2.1547},
       {1: 2.1547, 2: 0, 3: 4.2114},
       {2: 4.2114, 3: 0},
       {0: 2.4879, 4: 0}]

def findMax(data):
    return max(val for item in data for val in item.itervalues())

print "MAX", findMax(ddd)

Output:

MAX 4.2114

Upvotes: 2

Related Questions