1from collections import OrderedDict
2
3# Remembers the order the keys are added!
4x = OrderedDict(a=1, b=2, c=3)
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
1>>> # Tally occurrences of words in a list
2>>> cnt = Counter()
3>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
4... cnt[word] += 1
5>>> cnt
6Counter({'blue': 3, 'red': 2, 'green': 1})
7
8>>> # Find the ten most common words in Hamlet
9>>> import re
10>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
11>>> Counter(words).most_common(10)
12[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
13 ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
14
1
2# Dictionary where key values default to a list:
3 a = collections.defaultdict(list)
4# Dictionary where key values default to 0:
5 a = collections.defaultdict(int)
6# Dictionary where key values default to another dictionary:
7 a = collections.defaultdict(dict)
8
9'''
10Example:
11 In a regular dictionary, if you did the following:
12
13 a = {}
14 if a['apple'] == 1:
15 return True
16 else:
17 return False
18
19 You'd get an error, because 'apple' does not exist in dictionary.
20 However, if you use collections:
21
22 a = collections.defaultdict(int)
23 if a['apple'] == 1:
24 return True
25 else:
26 return False
27
28 This would not give an error, and False would be returned.
29 Also, the dictionary would now have the key 'apple' with a
30 default integer value of 0 inside it.
31
32 If you used say, collections.defaultdict(list), the default value
33 would be an empty list instead of 0.
34
35'''
36
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