views:

769

answers:

5

Here is the dictionary I have

propertyList = {
 "id":   "int",
 "name":   "char(40)",

 "team":   "int",
 "realOwner": "int",

 "x":   "int",
 "y":   "int",

 "description": "char(255)",

 "port":   "bool",
 "secret":  "bool",
 "dead":   "bool",
 "nomadic":  "bool",

 "population": "int",
 "slaves":  "int",
}

But when I print it out with "\n".join(myDict) I get this

name
nomadic
dead
port
realOwner
secret
slaves
team
y
x
population
id
description

I know that a dictionary is unordered but it comes out the same every time and I've no idea why.

+35  A: 

The real question should be “why not?” … an unordered dictionary is most probably implemented as a hash table (in fact, the Python documentation states this outright) where the order of elements is well-defined but not immediately obvious. Your observations match the rules of a hash table perfectly: apparent arbitrary, but constant order.

Konrad Rudolph
+1 Just a few seconds late :)
Stefano Driussi
It's well worth reading a comment from python's dictionary source file; I've already posted it in a stackoverflow post about "the best comment you've ever seen": http://is.gd/iSyN
llimllib
+4  A: 

The specification for the built-in dictionary type disclaims any preservation of order, it is best to think of a dictionary as an unordered set of key: value pairs...

You may want to check the ordereddict module, is an implementation of an ordered dictionary with Key Insertion Order.

CMS
+10  A: 

The definition of insanity is doing the same thing over and over again and expecting different results

-Einstein

... what does that have to do with anything?
Aaron Maenpaa
I think the point is that he's doing the same thing on a deterministic machine and getting the same results .. and that this should not be surprising.
John Fouhy
+3  A: 

The only thing about dictionary ordering you can rely on is that the order will remain the same if there are no modifications to the dictionary; e.g., iterating over a dictionary twice without modifying it will result in the same sequence of keys. However, though the order of Python dictionaries is deterministic, it can be influenced by factors such as the order of insertions and removals, so equal dictionaries can end up with different orderings:

>>> {1: 0, 2: 0}, {2: 0, 1: 0}
({1: 0, 2: 0}, {1: 0, 2: 0})
>>> {1: 0, 9: 0}, {9: 0, 1: 0}
({1: 0, 9: 0}, {9: 0, 1: 0})
Miles
A: 

But, if u are interested in order this is not the datastructure that you should be looking for. Dictionary is an unordered collection of items. List and Tuples preserve order.

Vijay