Search code examples
pythondictionaryordereddictionary

Python: iterating through a dict in the order in which items were inserted


d = { 'c' : 1, 'f': 2, 'a': 3}

for key, value in d.iteritems():
    print key

I want to be able to iterate through the keys in the order in which they were inserted.

I've looked at converting dict to OrderedDict but they seemed to be have some sort of order (not the order of their insertion)

Is there a easy way to convert dict to OrderedDict which maintains the order of insertion?


Solution

  • You shouldn't convert your dict to an OrderedDict, you should be using an OrderedDict in the first place:

    from collections import OrderedDict
    
    od = OrderedDict()
    od['c'] = 1
    od['f'] = 2
    od['a'] = 3
    

    Or often easier, create the OrderedDict from a list of tuples or a tuple of tuples:

    od = OrderedDict([('c', 1), ('f', 2), ('a', 3)])
    

    The problem with converting a dict to an OrderedDict is that as soon as you create a dict or add anything into it, the order is lost. So you can't use a dict at all if you need to keep the order.