0

If I have a list of dicts like:

l = [{'dist':56, 'responder':N}, {'dist':26, 'responder':N}, {'dist':86, 'responder':N}]

And I want to return the 2 smallest distances ('dist') as well as the value for 'responder', what is the best way to do that in Python?

CppLearner
  • 16,273
  • 32
  • 108
  • 163
user2767074
  • 267
  • 1
  • 4
  • 11
  • 1
    try `min(l, key=lambda d: d['dist'])`. – Bakuriu Nov 03 '13 at 23:15
  • @Cfreak, well I know that I can find the minimum distances by using a list comprehension and using min() but I still don't know how to retain the values of 'responder' – user2767074 Nov 03 '13 at 23:15
  • it is rare for a programming task to have `the best way` – alko Nov 03 '13 at 23:17
  • @Bakuriu's solution returns the smallest, but to return two of the smallest by sort, you should use ``sorted`` instead of ``min``. – CppLearner Nov 03 '13 at 23:18
  • @user2767074 the point is you should try something and see if it works. Then ask how to fix it if it doesn't. SO is not intended to be a place where people do your code for you. – Cfreak Nov 03 '13 at 23:19
  • 1
    `heapq.nsmallest` is quite a good way to find the 2 smallest of anything. – Steve Jessop Nov 03 '13 at 23:20
  • @Cfreak not necessarily. You'll see below that I got basic input from Bakuriu and was able to implement it on my own, thank you very much – user2767074 Nov 03 '13 at 23:26

2 Answers2

2

Try sort your list first

>>> from operator import itemgetter
>>> sorted(l, key=itemgetter('dist'), reverse=True)
[{'responder': 'N', 'dist': 86}, {'responder': 'N', 'dist': 56}, {'responder': 'N', 'dist': 26}]

then slice first two elements

>>> sorted(l, key=itemgetter('dist'), reverse=True)[:2]
[{'responder': 'N', 'dist': 86}, {'responder': 'N', 'dist': 56}]

and get responders from them

>>> map(itemgetter('responder'), sorted(l, key=itemgetter('dist'), reverse=True)[:2])
['N', 'N']
alko
  • 46,136
  • 12
  • 94
  • 102
  • I know about heapq, and advocate it, but cosider it a bit complicated for this question – alko Nov 03 '13 at 23:23
1

Using @Bakuriu's solution with a modification:

l = [{'dist':56, 'responder':'n'}, {'dist':26, 'responder':'n'}, \
{'dist':86, 'responder':'n'}]

smallestTwo = sorted(l, key=lambda d: d['dist'])[:2]

Output:

[{'responder': 'n', 'dist': 26}, {'responder': 'n', 'dist': 56}]
user2767074
  • 267
  • 1
  • 4
  • 11