Monday 2 January 2017

Sort a python Dictionary by Value

You cannot  sort a dictionary, but only get a representation of a dictionary that is sorted. Dictionary are inherently order-less, but other types such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples.

Sort a python Dictionary by value:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

Sort a python Dictionary by Key:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))