"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}
}
CodePudding user response:
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
.