Finding minimum value in an array of dicts

Question:

I have an array like the following:

people = [{'node': 'john', 'dist': 3}, 
          {'node': 'mary', 'dist': 5}, 
          {'node': 'alex', 'dist': 4}]

I want to compute the minimum of all the ‘dist’ keys. For instance, in the above example, the answer would be 3.

I wrote the following code:

min = 99999
for e in people:
    if e[dist] < min:
        min = e[dist]
print "minimum is " + str(min)

I am wondering if there is a better way to accomplish this task.

Asked By: Vivek Pandey

||

Answers:

Use the min function:

minimum = min(e['dist'] for e in people)
# Don't call the variable min, that would overshadow the built-in min function
print ('minimum is ' + str(minimum))
Answered By: phihag
min(x['dist'] for x in people)
Answered By: clyfish

You could use a generator expression to create a list with all keys and then use the built-in min function:

min(x['dist'] for x in people)
Answered By: leoluk
min(people, key=lambda x:x['dist'])['dist']
Answered By: riza
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.