python orderd dict code example

Example 1: python counter

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

Example 2: OrederedDict

import collections
#dictionnarry that remembers the order in which the items where given
print 'Regular dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v

print '\nOrderedDict:'
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v
    
>>>$ python collections_ordereddict_iter.py

Regular dictionary:
a A
c C
b B
e E
d D

OrderedDict:
a A
b B
c C
d D
e E

Tags:

Misc Example