Examples of sorting methods for dictionaries of dict and lists of list in Python

  • 2020-04-02 13:46:26
  • OfStack

1. Sort the list

The recommended way to sort is to use the built-in sort() method, which is the fastest and most stable sort


>>> a = [1,9,3,7,2,0,5]
>>> a.sort()
>>> print a
[0, 1, 2, 3, 5, 7, 9]
>>> a.sort(reverse=True)
>>> print a
[9, 7, 5, 3, 2, 1, 0]
>>> b = ['e','a','be','ad','dab','dbc']
>>> b.sort()
>>> print b
['a', 'ad', 'be', 'dab', 'dbc', 'e']

Sort of list is following the DSU (decorate - sort - undecorate) model, the sequence is to install the entry sequence comparison, for example just the string is in the order from left to right, each character comparison, once the results will stop.

Second, sort dict

Dict is an unordered sequence, so we can't sort it, we can only sort it by the keys/values of the dictionary, and then we can put the corresponding values/keys in the same order
Any sorting of dictionaries boils down to sorting a list of dict keys or values

1. Sort by dict [1]


def sortedDictValues(adict,reverse=False):
 keys = adict.keys()
 keys.sort(reverse=reverse)
 return [adict[key] for key in keys]

If you need to return both the key and the value, change the last return statement to:
return [(key,adict[key]]) for key in keys]

Another easy way to write is to use the built-in sorted() method:

>>> d = {'c':1,'e':'5','b':7}
>>> sorted(d.items())
[('b', 7), ('c', 1), ('e', '5')]

However, there is a slight degradation in performance, so if you are demanding performance, it is better to use the native list.sort() method

2. Sort by dict [2]


def sorted_dict(container, keys, reverse):
 """ return  keys  The list of , According to the container The corresponding value sort in """
 aux = [ (container[k], k) for k in keys]
 aux.sort()
 if reverse: aux.reverse()
 return [k for v, k in aux]

We can also use the sorted() method to achieve the same function:
sorted(d.items(), key=lambda d:d[1], reverse=True)

Three, endnotes

Through the above code analysis, the general summary of the following principles:
* sorting dictionaries, in the end, comes down to sorting lists of keys or values of dictionaries
* sort lists, using the built-in list.sort() method in preference


Related articles: