0

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.

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.