python ordereddict example

Example 1: ordered dictionary python

from collections import OrderedDict

# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)

Example 2: how to make an ordered dictionary in python

# A Python program to demonstrate working of key  
# value change in OrderedDict 
from collections import OrderedDict 
  
print("Before:\n") 
od = OrderedDict() 
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items(): 
    print(key, value) 
  
print("\nAfter:\n") 
od['c'] = 5
for key, value in od.items(): 
    print(key, value) 
""" 
Ouptut:
Before:

('a', 1)
('b', 2)
('c', 3)
('d', 4)

After:

('a', 1)
('b', 2)
('c', 5)
('d', 4)
"""

Example 3: ordered dictionary python

import collections

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