2

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Vivek Pandey
  • 3,455
  • 1
  • 19
  • 25

4 Answers4

8

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))
phihag
  • 278,196
  • 72
  • 453
  • 469
3
min(x['dist'] for x in people)
clyfish
  • 10,240
  • 2
  • 31
  • 23
3

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)
leoluk
  • 12,561
  • 6
  • 44
  • 51
0
min(people, key=lambda x:x['dist'])['dist']
riza
  • 16,274
  • 7
  • 29
  • 29