We all know that dictionaries are unordered, how do we sort them according to the dictionary key or value?
Sort by key of the dictionary
Available in three ways:
1. Using lambda
>>> a = {‘b‘:‘a‘,‘d‘:‘d‘,‘a‘:‘a‘}>>> sorted(a.items(),key=lambda x:x[0])[(‘a‘, ‘a‘), (‘b‘, ‘a‘), (‘d‘, ‘d‘)]
2. Using operator module
>>> import operator>>> sorted(a.items(),key=operator.itemgetter(0))[(‘a‘, ‘a‘), (‘b‘, ‘a‘), (‘d‘, ‘d‘)]
3. Direct use of sorted
The dictionary key is sorted by default
>>> sorted(a.items())[(‘a‘, ‘a‘), (‘b‘, ‘a‘), (‘d‘, ‘d‘)]
Sort by value of dictionary
Available in two ways:
1, use lambda, change the index can be
>>> a = {‘a‘:‘d‘,‘b‘:‘a‘,‘c‘:‘b‘}>>> sorted(a.items(),key=lambda x:x[1])[(‘b‘, ‘a‘), (‘c‘, ‘b‘), (‘a‘, ‘d‘)]
2, the use of operator, but also change the index can be
>>> import operator>>> sorted(a.items(),key=operator.itemgetter(1))[(‘b‘, ‘a‘), (‘c‘, ‘b‘), (‘a‘, ‘d‘)]
It is important to note that sorted () does not change its value by default, just return a result
Just wrap it up with the Dict function:
>>> a = dict(sorted(a.items(),key=lambda x:x[0]))>>> a{‘a‘: ‘d‘, ‘b‘: ‘a‘, ‘c‘: ‘b‘}
Python dictionary sort