How to sort Dictionaries over values?

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So we need a sorted representation, which will be a list—probably a list of tuples.
Soln 1 :
To sort on values :
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple.dict(sorted_x) == x

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

Soln 2 :
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted( x.items(), key=lambda a : a[1] )

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?