Python 2.7 Dict with key value pairs of lists is reordered
Question: I'm trying to use a dict of key value pairs to store and access lists based on
the appropriate keys. Below is what I'm using.

    
    
    newDict = {'mod':[0,2], 'pro':[2,3], 'st':[6,10]}
    newDict2 = {'a':[0,2], 'b':[2,3], 'c':[6,10]}
    

I'm building this dict in a specific order so I can iterate through it with a
`for` loop. But for whatever reason when I print or put it through a `for`
loop the order of the keys is reordered.

    
    
    print "the newDict is: " + str(newDict)
    print "the newDict2 is: " + str(newDict2)
    for key in newDict:
        print "the key is: " + str(key)
    

The output of this is below.

    
    
    newDict is: {'pro': [2, 3], 'mod': [0, 2], 'st': [6, 10]}
    newDict2 is: {'a': [0, 2], 'c': [6, 10], 'b': [2, 3]}
    the key is: pro
    the key is: mod
    the key is: st
    

I'm more concerned with the order of the keys than the values of the lists. So
I don't want to order it by the values of the lists. I've been doing research
but can't figure out why it's changing the order. I've tried changing the
values in the lists to try and figure it out but I haven't been able to find a
pattern. I thought dict's were used when order wasn't a concern. Maybe dicts
aren't the way to go about this. Any help is greatly appreciated.


Answer: As you mention, python dictionaries do not maintain order. This means that you
are not guaranteed to get out the key value pairs in any order when printing
the `dict` or iterating over it after it is created or modified. However, this
order, whatever it is, will be maintained as long as no items are inserted or
removed.

The lists in your `dict`, which are values corresponding to keys, are not
changing; they still match the keys they were assigned to. However, the order
of the key value pairs has changed.

You can use an `OrderedDict` if you would like the key value pairs to maintain
order.

    
    
    from collections import OrderedDict
    newDict = OrderedDict([('mod', [0,2]), ('pro',[2,3]), ('st',[6,10])])
    newDict2 = OrderedDict([('a',[0,2]), ('b',[2,3]), ('c',[6,10])])
    

