OrderedDict

  • Return an instance of a dict subclass
  • remembers the order that keys were first inserted

Initialization

In [ ]:
from collections import OrderedDict

d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
o = OrderedDict(d) # OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])

# insert item
o['pineapple'] = 10 # OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2), ('pineapple', 10)])

Methods

In [ ]:
item = o.popitem() #('pineapple', 10), the pairs are returned in LIFO order if last is true or FIFO order if false
print(o) # OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])

o.move_to_end('apple') # the item is moved to the right end if last is true or to the beginning if last is false
print(o) # OrderedDict([('banana', 3), ('pear', 1), ('orange', 2), ('apple', 4)])

Dict Methods

  • supporting the usual dict methods
In [ ]:
k = list(o.keys()) # ['banana', 'pear', 'orange', 'apple']
v = list(o.values()) # [3, 1, 2, 4]
i = list(o.items()) # [('banana', 3), ('pear', 1), ('orange', 2), ('apple', 4)]
#o.clear() # empty

Built-in Functions

In [ ]:
print(len(o)) # 4
print(list(o)) # ['banana', 'pear', 'orange', 'apple']