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"""
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