I just stumbled upon an ordered dict in Python and had to look it up. So here you can find how an ordered dict differs from a normal dict and why it is useful.

### Dictionaries in Python

Dictionary is a common object type in Python: Dictionaries are usually a set of key value pairs. They are usually defined in the following way:

1 2 3 |
>>>dict = {} # empty dictionary >>>dict = {'key1':'value1, 'key2':'value2', ... } # definition of a dictionary >>>dict['key3'] = 'value3' # sucessive definition of key value pairs |

Other as lists dictionaries do not have an order. You can iterrate over them, but Python can serve you the key value pairs in any order.

1 2 3 |
>>>color_dict = {'red':0, 'blue':1} >>>color_dict {'blue':1, 'red':0} # Python iterates in its own order |

### What is point in ordered dicts?

The point there is that the dictionary remembers the sequence in which you entered the key value pairs and if you iterate Python will stick to that sequence.

An ordered dictionary looks like this:

1 2 3 4 |
>>>from collections import OrderedDict >>>color_ordereddict = OrderedDict([('red',0), ('blue',1)]) >>>color_ordereddict OrderedDict([('red', 0), ('blue', 1)]) # Python respects the order |

OrderedDict([(‘red’, 0), (‘blue’, 1)])

**Can you order a ordered dict?**

Yes you can, but remember when you add elements after you ordered it, they will be put to the back. The Ordered Dict does not know who you ordered it. It just knows, the order you gave him and the order of elements added to it:

1 2 3 4 5 6 |
>>>alphabethic_ordered = OrderedDict(sorted(color_ordereddict.items(),key=lambda t:t[0])) >>>alphabethic_ordered OrderedDict([('blue', 1), ('red', 0)]) >>>numerical_ordered = OrderedDict(sorted(color_ordereddict.items(),key=lambda t:t[1])) >>>numerical_ordered OrderedDict([('red', 0), ('blue', 1)]) |

### Can you compare to the ordinary dict?

yes you can: remember Python is duck typing, which means it always tries to guess what you want to do: so if you compare two OrderedDicts it will compare the order as well, but an OrderedDict will be equal to a regular Dict as long as it has the same key value pairs

1 2 3 4 5 6 |
>>>alphabethic_ordered == numerical_ordered False >>>alphabethic_ordered == color_dict True >>>numerical_ordered == color_dict True |

So with Python’s duck typing the logical operator == is not transitive as you see!

### Source

https://docs.python.org/2/library/collections.html#collections.OrderedDict

## Leave a Reply