7

I'm just starting to play around with Python (VBA background). Why does this dictionary get created out of order? Shouldn't it be a:1, b:2...etc.?

class Card:
def county(self):
    c = 0
    l = 0
    groupL = {}  # groupL for Loop
    for n in range(0,13):
        c += 1
        l = chr(n+97)
        groupL.setdefault(l,c)
    return groupL

pick_card = Card()
group = pick_card.county()
print group

here's the output:

{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12}

or, does it just get printed out of order?

DBWeinstein
  • 8,605
  • 31
  • 73
  • 118
  • 1
    As a side note, why are you using setdefault here? There are plenty of cases where that's a useful function, but for just inserting stuff into a dictionary, `groupL[l] = c` is probably what you want. – abarnert Aug 02 '12 at 23:35
  • Possible duplicate of [Python dictionary, how to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-in-same-order-as-declared) – Arya McCarthy May 29 '17 at 02:47

1 Answers1

17

Dictionaries have no order in python. In other words, when you iterate over a dictionary, the order that the keys/items are "yielded" is not the order that you put them into the dictionary. (Try your code on a different version of python and you're likely to get differently ordered output). If you want a dictionary that is ordered, you need a collections.OrderedDict which wasn't introduced until python 2.7. You can find equivalent recipes on ActiveState if you're using an older version of python. However, often it's good enough to just sort the items (e.g. sorted(mydict.items()).

EDIT as requested, an OrderedDict example:

from collections import OrderedDict
groupL = OrderedDict()  # groupL for Loop
c = 0
for n in range(0,13):
    c += 1
    l = chr(n+97)
    groupL.setdefault(l,c)

print (groupL)
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • First, thanks! But, why would the numbers and letters go in specifically out of order? They are being entered in order via the loop, no? Regardless, could you give an quick example of collections.OrderedDict? Many thanks. – DBWeinstein Aug 02 '12 at 20:02
  • 1
    @dwstein Virtually all Python implementations use [hash maps](http://en.wikipedia.org/wiki/Hash_map) to allow extremely fast access to the dictionary's values by key. – phihag Aug 02 '12 at 20:04
  • 2
    @dwstein: It *doesn't matter* what order they are entered in. – David Robinson Aug 02 '12 at 20:07
  • I think i'm getting it. the fact that it doesn't matter is interesting. going to have to wrap my brain around that. – DBWeinstein Aug 02 '12 at 20:11
  • @dwstein, if you're really insterested in what is hidden inside Python's dict, I strongly recommend you to read this article: http://www.laurentluce.com/posts/python-dictionary-implementation/ – Rostyslav Dzinko Aug 02 '12 at 20:14
  • @RostyslavDzinko -- That's quite a gem. Thanks! (I assume that is Cpython specific, but still quite neat). – mgilson Aug 02 '12 at 20:18
  • 5
    @dwstein: it might help to think of a literal dictionary (as in "Merriam-Webster"). New words and definitions can be added to a dictionary with every new edition. But the order they're stored in has nothing to do with the order that they're added. They are stored in the order that makes it easiest to look them up. Python dictionaries work the same way. – David Robinson Aug 02 '12 at 20:20
  • @DavidRobinson -- I never thought of it that way. Interesting. I've always been trying to avoid thinking about a literal dictionary because the order those are stored in are so obvious and `dict` objects have no obvious order (*to me*). I never thought about how the order is the "obvious" one *for the computer*. – mgilson Aug 02 '12 at 20:32
  • Unlike a physical dictionary, though, adding an element to a Python dict can cause all the other elements to be reordered. – Russell Borogove Aug 02 '12 at 20:45