1>>> # regular unsorted dictionary
2>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
3
4>>> # dictionary sorted by key
5>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
6OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
7
8>>> # dictionary sorted by value
9>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
10OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
11
12>>> # dictionary sorted by length of the key string
13>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
14OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
15
1most_common([n])¶
2Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.
3Elements with equal counts are ordered arbitrarily:
4
5>>> Counter('abracadabra').most_common(3)
6[('a', 5), ('r', 2), ('b', 2)]
7