Changing order of ordered dictionary in python
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)
Edit: You can write a custom function (warning, this works but is very quick and dirty):
EDIT: Fixed bug that occurs when you try to move forward
import collections
def move_element(odict, thekey, newpos):
odict[thekey] = odict.pop(thekey)
i = 0
for key, value in odict.items():
if key != thekey and i >= newpos:
odict[key] = odict.pop(key)
i += 1
return odict
queue = collections.OrderedDict()
queue["animals"] = ["cat", "dog", "fish"]
queue["food"] = ["cake", "cheese", "bread"]
queue["people"] = ["john", "henry", "mike"]
queue["drinks"] = ["water", "coke", "juice"]
queue["cars"] = ["astra", "focus", "fiesta"]
print queue
queue = move_element(queue, "people", 1)
print queue
I think you'll have to do it manually:
>>> keys = list(queue)
>>> keys
['animals', 'food', 'people', 'drinks']
>>> keys[1], keys[2] = keys[2], keys[1]
>>> queue = collections.OrderedDict((key, queue[key]) for key in keys)
>>> list(queue)
['animals', 'people', 'food', 'drinks']