0

I am trying to make a leaderboard in python and I have the following dict: points = [("Bob",12),("Steve",7),("Alice",9)] I am trying to sort it into the following dict: points = [("Bob",12),("Alice",9),("Steve",7)] How would I do this programatically.

I have tried sorteddata = sorted(data,key=itemgetter(1)) to no avail.

Thanks in advance, - Evan

EGE
  • 69
  • 6
  • 2
    `reverse=True` will help. [Docs](https://docs.python.org/3/library/functions.html#sorted). – Olvin Roght May 27 '20 at 18:56
  • Try `print(sorted(points, key=lambda x: (-x[1], x[0])))` – Anwarvic May 27 '20 at 18:56
  • This should help - https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index – Pavel Štěrba May 27 '20 at 18:56
  • That's not really a two-dimensional array, as the two "columns" can't vary freely. – chepner May 27 '20 at 18:56
  • 2
    Does this answer your question? [How to sort a list/tuple of lists/tuples by the element at a given index?](https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) – Pavel Štěrba May 27 '20 at 18:56
  • `..to no avail.` - why doesn't this work? `I have the following dict: ..` - `points` is not a dict, it is a list. – wwii May 27 '20 at 19:07

2 Answers2

0

You can do this:-

pts = list(points)
pts.sort(key=lambda x:x[1], reverse=True)

Output:-

[('Bob', 12), ('Alice', 9), ('Steve', 7)]
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
  • The only problem I have with this answer is that you are trying to sort a python dict object, which returns with a AttributeError. – EGE May 27 '20 at 19:00
  • @EGE, You can then convert it into a list first to sort. I have updated the code. Hope this solves your error – Dhaval Taunk May 27 '20 at 19:03
0

The SortedDict in the sortedcontainers package serves as a dict object with sorted keys. (http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html)

To sort by values, there is also the ValueSortedDict in sortedcollections.(http://www.grantjenks.com/docs/sortedcollections/valuesorteddict.html)

Otherwise, a pure builtin function like this might help:

def sort_dict_by_values(dictionary):
    return dict(sorted(list(dictionary), key=lambda tup: tup[1], reverse=True))
Eric Musa
  • 1
  • 1
  • 1