0
Q:

how to make an ordered dictionary in python

from collections import OrderedDict

# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
1
An OrderedDict is a dictionary subclass that remembers the order 
that keys were first inserted. A regular dict doesn’t track the 
insertion order, and iterating it gives the values in an arbitrary 
order.
# A Python program to demonstrate working of OrderedDict 
from collections import OrderedDict 
d = {} # regular dict
d['a'] = 1
d['b'] = 2
d['c'] = 3
for key, value in d.items(): 
    print(key, value) 
# Output
# ('a', 1)
# ('c', 3)
# ('b', 2)  
od = OrderedDict() # Ordered Dict
od['a'] = 1
od['b'] = 2
od['c'] = 3
for key, value in od.items(): 
    print(key, value) 
# Output
# ('a', 1)
# ('b', 2)
# ('c', 3)
1
# 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)
"""
0
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
    
0

New to Communities?

Join the community