1

I have the following piece of code in python:

results = {}
....
results = sorted([(v, k) for (k, v) in results.items()])
....
return results[:limit]

results contains distances that are sorted in such a way the smaller distances are in the top of the list

Is there a way to sort this list in such a way the higher distances are in the top of results? Or, if we don't reverse the items is there a way to get the last items of results instead of the top results using return results[:limit]

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Safiya
  • 185
  • 1
  • 3
  • 11
  • 1
    you probably want `reverse=True` or/and `heapq` module – Jean-François Fabre Sep 19 '18 at 16:26
  • Do you care only for the top (or bottomly) ranked item? If so, you should look into using heaps (with the [heapq](https://docs.python.org/3/library/heapq.html?highlight=heapq) library). – Sunny Patel Sep 19 '18 at 16:26
  • Is it necessary to change the structure of `results`? If not, you can utilize the `key=` parameter of `sorted` to accomplish the same: `results = sorted(results.items(), key=lambda n: n[1], reverse=False)` – Sunny Patel Sep 19 '18 at 16:31

2 Answers2

1

Use the optional reverse parameter in the sorted function:

results= sorted([(v, k) for (k, v) in results.items()], reverse=True)
Ruzihm
  • 19,749
  • 5
  • 36
  • 48
0

To answer the second question you ask, since @Ruzihm already answered the first, you can get the last items of results with:

return results[-limit:]
blhsing
  • 91,368
  • 6
  • 71
  • 106