We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Let's you have a Python dictionary and you want to get a representation of it sorted by the value.
Method 1:
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Method 2:
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.