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)]

Related Posts

  • Making a unique list in Python preserving the order
  • Testing exceptions in pytest
  • Annotate Querysets to Fetch Specific Values
  • Optimize Database Calls with Prefetch Related and Select Related
  • Executing a Python function and fail after x attempts