pythonpython-2.7collectionsordereddictionary

Changing order of ordered dictionary in python


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

Solution

  • You can write a custom function (warning, this works but is very quick and dirty):

    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