What is an OrderedDict in Python?
An OrderedDict is a dictionary subclass in which the order of the content added is maintained.
import collectionsordered_dict = collections.OrderedDict()ordered_dict['one'] = 1ordered_dict['two'] = 2ordered_dict['three'] = 3print(ordered_dict)
-
When we add a new element, it will be inserted at the end.
-
When we delete an element, the element below it will move to the deleted element’s position.
-
When we change the value of an element, the element will stay in same order.
import collectionsordered_dict = collections.OrderedDict()ordered_dict['one'] = 1ordered_dict['two'] = 2ordered_dict['three'] = 3print(ordered_dict)print("\n-------\nAdding new element")ordered_dict['four'] = 4print(ordered_dict)print("\n-------\nDeleting an element")ordered_dict.pop('two');print(ordered_dict)print("\n-------\nReplacing value of an element")ordered_dict['one'] = "one";print(ordered_dict)
We can use move_to_end to move an element either to the first or the last element of the dictionary.
The second argument of the
move_to_endmethod determines the position.
So, if we pass true it will reposition the element to the last position; however, if we pass false, then the element is repositioned to the first position.
import collectionsordered_dict = collections.OrderedDict()ordered_dict['one'] = 1ordered_dict['two'] = 2ordered_dict['three'] = 3print(ordered_dict)print("\n---------\nMoving 'one' as last element")ordered_dict.move_to_end('one');print(ordered_dict);print("\n---------\nMoving 'three' as first element")ordered_dict.move_to_end('three', False);print(ordered_dict);
To iterate the OrderedDict in reverse order, use reversed method.
import collectionsordered_dict = collections.OrderedDict()ordered_dict['one'] = 1ordered_dict['two'] = 2ordered_dict['three'] = 3print(ordered_dict)print("\nReversed order")for prop in reversed(ordered_dict):print(prop);
When checking for dict equality:
-
A regular dict looks at its contents
-
An OrderedDict looks at the order and the contents
import collections;d1 = {'1': 1, '2': 2}d2 = {'2': 2, '1': 1}print("Cheking if two normal dic are equal => ", d1 == d2);ordered_dict_1 = collections.OrderedDict({'1': 1, '2': 2})ordered_dict_2 = collections.OrderedDict({'2': 2, '1': 1})print("Cheking if two ordered dic are equal => ", ordered_dict_1 == ordered_dict_2);