0

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.

user2743
  • 1,423
  • 3
  • 22
  • 34

2 Answers2

2

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])])
bnjmn
  • 4,508
  • 4
  • 37
  • 52
  • 3
    There are some guarantees, but they're pretty minimal -- e.g. you're guaranteed that the order of the dictionary will always be consistent if you iterate over it multiple times so long as you don't insert or remove any items ... – mgilson Feb 15 '14 at 04:15
1

Sorry for the lag I am having internet problems

from collections import OrderedDict

so that is a special container that is an OrderedDict, it is Ordered by the sequence of key insertion, the keys will maintain their order sequentially.

so you have some process to create the keys,

newDict = OrderedDict()

for some_iterator_value in some_iterator:
    key = some_iterator_value
    value = we_created_a_list
    newDict[key] = value
PyNEwbie
  • 4,882
  • 4
  • 38
  • 86