-1
"users": {
    "673336994218377285": {"votes": 5},
    "541388453708038165": {"votes": 1},
    "845444326065700865": {"votes": 9}
}

How can I sort a dictionary depending on the "votes" key of the nested dictionary? The dictionary should look like this:

"users": {
    "845444326065700865": {"votes": 9},
    "673336994218377285": {"votes": 5},
    "541388453708038165": {"votes": 1}
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
FoxGames01
  • 67
  • 1
  • 7
  • 1
    [https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) This link should help. – pietnam Sep 24 '21 at 22:19
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Adrian Mole Sep 25 '21 at 22:30

1 Answers1

4

Dictionaries in Python (since 3.6) are sorted by their insertion order, so you have to create a new dictionary with the elements inserted in their sorted order:

users = {
    "673336994218377285": {"votes": 5},
    "541388453708038165": {"votes": 1},
    "845444326065700865": {"votes": 9}
}

dict(sorted(users.items(), key=lambda x: x[1]['votes'], reverse=True))

The key=lambda x: x[1]['votes'] makes it sort each element according to the 'votes' field of the value of each item.

If you're using an older version of Python then dictionaries will not be sorted, so you'll have to use this same approach with collections.OrderedDict instead of dict.

Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
  • 2
    A short explanation for the 1 liner solution. The collection we sort is the dict `items`. It is a tuple with 2 slots: 0 -> key, 1 -> value. This is why the `lambda` uses `x[1]['votes']` – balderman Sep 24 '21 at 22:22