2

So I have a dictionary in python in which I have a number for the key with a value attatched to it.

myDictionary = {"0" :0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":12, "7":0,"8":0,"9":0,"10":0,"11":0, "12":0,"13":12}

I run a doctest that says:

>>> myDictionary = {"0" :0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":12, "7":0,"8":0,"9":0,"10":0,"11":0, "12":0,"13":12}
>>> new_Val = 0
>>> method0 = WordClass (new_Val, myDictionary)
True

I was doing some debugging ad printed out my dictionary to make sure I was going through the right values in the dictionary. When I printed it out, it looked like this:

{'11': 4, '10': 4, '13': 0, '12': 4, '1': 4, '0': 4, '3': 4, '2': 4, '5': 4, '4': 4, '7': 4, '6': 0, '9': 4, '8': 4}

They are all out of order. Does python do that by default when storing memory or something? If so, is there some documentation somewhere that I can look at?

Thank you

JustBlossom
  • 1,259
  • 3
  • 24
  • 53
  • 1
    [Dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) are unordered by definition. Why not use a list? – Tim Pietzcker Apr 11 '14 at 17:33

2 Answers2

5

Dictionaries in python are unordered. Do you actually need an order? If you elaborate on this a bit people may be able to help you more. You can try using something like https://docs.python.org/2/library/collections.html#collections.OrderedDict if you really need it to be ordered.

user3499545
  • 186
  • 4
  • Well, they have to be ordered to iterate through them right? I want to be able to get the value at each one going through a for loop – JustBlossom Apr 11 '14 at 17:42
  • @LearnLanguages96, you can't iterate through a ```dict``` directly. What you can do is generate a list of keys, and then loop through that and sequentially call up the values. This is what implicitly happens when you do ```for thing in a_dict:```, each ```thing``` will be a key of the dictionary ```a_dict``` (which pops up in an arbitrary order) – wnnmaw Apr 11 '14 at 17:45
  • 1
    Why do they need to be ordered? You could do `for key in dict` or `for item in dict.items()` with no expectation of getting them back in any particular order, or even the same order twice. – Larry Lustig Apr 11 '14 at 17:53
1

Python dictionary keys are unordered. If you want them back in a particular order, you need to sort them. If you want a dictionary to remember the order in which keys were added, use OrderedDict() from collections.

More info: https://docs.python.org/3.3/library/collections.html#collections.OrderedDict

Larry Lustig
  • 49,320
  • 14
  • 110
  • 160