1from collections import OrderedDict
2
3# Remembers the order the keys are added!
4x = OrderedDict(a=1, b=2, c=3)
1import collections
2
3print 'Regular dictionary:'
4d = {}
5d['a'] = 'A'
6d['b'] = 'B'
7d['c'] = 'C'
8d['d'] = 'D'
9d['e'] = 'E'
10
11for k, v in d.items():
12 print k, v
13
14print '\nOrderedDict:'
15d = collections.OrderedDict()
16d['a'] = 'A'
17d['b'] = 'B'
18d['c'] = 'C'
19d['d'] = 'D'
20d['e'] = 'E'
21
22for k, v in d.items():
23 print k, v
24
25
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# A Python program to demonstrate working of key
2# value change in OrderedDict
3from collections import OrderedDict
4
5print("Before:\n")
6od = OrderedDict()
7od['a'] = 1
8od['b'] = 2
9od['c'] = 3
10od['d'] = 4
11for key, value in od.items():
12 print(key, value)
13
14print("\nAfter:\n")
15od['c'] = 5
16for key, value in od.items():
17 print(key, value)
18"""
19Ouptut:
20Before:
21
22('a', 1)
23('b', 2)
24('c', 3)
25('d', 4)
26
27After:
28
29('a', 1)
30('b', 2)
31('c', 5)
32('d', 4)
33"""
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
1sum(c.values()) # total of all counts
2c.clear() # reset all counts
3list(c) # list unique elements
4set(c) # convert to a set
5dict(c) # convert to a regular dictionary
6c.items() # convert to a list of (elem, cnt) pairs
7Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
8c.most_common()[:-n-1:-1] # n least common elements
9c += Counter() # remove zero and negative counts
10