Changing order of ordered dictionary in python

speedyrazor picture speedyrazor · Mar 26, 2014 · Viewed 15k times · Source

I have an ordered dictionary and want to change the individual order. In the below code example I want to item 3 (people), along with its values, to move to position 2. So the order will be animals, people, food, drinks. How do I go about his?

import collections

queue = collections.OrderedDict()

queue["animals"] = ["cat", "dog", "fish"]
queue["food"] = ["cake", "cheese", "bread"]
queue["people"] = ["john", "henry", "mike"]
queue["drinks"] = ["water", "coke", "juice"]

print queue

Answer

dannymilsom picture dannymilsom · Mar 26, 2014

OrderedDicts are ordered by insertion order. So you would have to construct a new OrderedDict by looping over the key:value pairs in the original object. There is no OrderedDict method that will help you.

So you could create a tuple to represent the idea order of the keys, and then iterate over that to create a new OrderedDict.

key_order = ('animal', 'people', 'food', 'drink')
new_queue = OrderedDict()
for k in key_order:
    new_queue[k] = queue[k]

Or more eloquently

OrderedDict((k, queue[k]) for k in key_order)