Home > Back-end >  Sort Dictionary Python
Sort Dictionary Python

Time:03-04

I have a dictionary for example like {"abc": 3, "dcb": 4, "dab": 4, "dfb": 5}. I would like to sort it by value and by keys, where the value is more important than the key. So in our example we would get:

{"dfb" : 5, "dab" : 4, "dcb" : 4, "abc" : 3}

More preferably if it is presented as a list rather than dictionary.

CodePudding user response:

You could use sorted on the dictionary items with the reversed order as key to make the value the major key, and negative value for descending order:

sorted(d.items(), key=lambda x: (-x[1], x[0]))

Output:

[('dfb', 5), ('dab', 4), ('dcb', 4), ('abc', 3)]

NB. the exact expected output is unclear but you can easily convert to dictionary or list of lists from there

dict(sorted(d.items(), key=lambda x: (-x[1], x[0])))
# {'dfb': 5, 'dab': 4, 'dcb': 4, 'abc': 3}
  • Related