#pattern #python

Let's you have a Python dictionary and you want to get a representation of it sorted by the value.

Method 1:

1>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
2
3>>> sorted(xs.items(), key=lambda x: x[1])
4[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

Method 2:

1>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
2
3>>> import operator
4>>> sorted(xs.items(), key=operator.itemgetter(1))
5[('d', 1), ('c', 2), ('b', 3), ('a', 4)]