Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. Both ordered dictionary and the built-in dict can remember insertion order. Some differences from dict are:
- Regular dict is efficient at mapping operations, but tracking insertion order is secondary. OrderedDict in Python is efficient in reordering operations, but iteration speed, and the performance of update operations is secondary.
- Equality operation for OrderedDict checks for matching order.
- popitem() method of OrderedDict has a different signature.
Syntax
To create ordered dictionary, syntax is
collections.OrderedDict([items])
It return an instance of a dict subclass that has methods specialized for rearranging dictionary order.
Important Methods
OrderedDict supports usual mapping methods.
- popitem(last=True) : Returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.
- move_to_end(key, last=True) : Move an existing key to either end of an ordered dictionary. If last is true, item is moved to the right end else in the beginning.
Example
Below example creates two ordered dictionary. First dictionary is created by adding key and value, while other dictionary is created using list. To get the winning team, popitem() is used.
# Demonstrate the usage of OrderedDict objects from collections import OrderedDict # 1. Create OrderedDict d = OrderedDict() d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) # Output # a A # b B # c C # Teams with scores sportTeams = [("Royals", 18), ("Rockets", 24), ("Dragons", 22), ("Kings", 15), ("Jets", 16), ("Warriors", 25)] # Sort the teams sortedTeams = sorted(sportTeams, key=lambda t: t[1], reverse=True) # 2. Create an ordered dictionary of the teams teams = OrderedDict(sortedTeams) print(teams) # Output # OrderedDict([('Warriors', 25), ('Rockets', 24), ('Dragons', 22), ('Royals', 18), ('Jets', 16), ('Kings', 15)]) # Remove the top item tm, wl = teams.popitem(False) print("Top team: ", tm, wl) # Output # Top team: Warriors 25
Reverse Order
OrderedDict also support reverse iterator, which is not supported in regular dictionary. Below example get the keys of dictionary in reverse order and traverse using for loop. reversed() return a reverse iterator.
# Demonstrate the usage of OrderedDict objects from collections import OrderedDict # 1. Create OrderedDict d = OrderedDict() d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) # Output # a A # b B # c C itr = reversed(d) for k in itr: print(k, d[k]) # Output # c C # b B # a A
Reordering
It is possible to change the order of the keys in an OrderedDict by moving them to either beginning or end of using move_to_end().
import collections d = collections.OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')]) print(d) # Output : Initial Order # OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')]) d.move_to_end('b') print(d) # Output : Order after move_to_end # OrderedDict([('a', 'A'), ('c', 'C'), ('b', 'B')])
Equality
A regular dict looks at its contents when testing for equality. An OrderedDict also considers the order in which the items were added. Equality tests between OrderedDict objects and other Mapping objects are order-insensitive like regular dictionaries. So OrderedDict objects can be substituted anywhere a regular dictionary is used.
import collections d1 = collections.OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')]) d2 = collections.OrderedDict([('b', 'B'), ('a', 'A'), ('c', 'C')]) d3 = collections.OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')]) d4 = {} d4['a'] = 'A' d4['b'] = 'B' d4['c'] = 'C' d5 = {} d5['b'] = 'B' d5['c'] = 'C' d5['a'] = 'A' # Ordered Dict equality print(d1 == d2) # Output # False print(d1 == d3) # Output # True # Regular Dict equality print(d4 == d5) # Output # True print(d1 == d5) # Output # True