Dict ordering [was: Re: MySQLdb and ordering of column names in list returned by keys() w/ a DictCursor]

Tim Wintle tim.wintle at teamrubber.com
Thu Jul 2 12:49:48 EDT 2009


On Thu, 2009-07-02 at 10:32 -0500, Wells Oliver wrote:
> for row in cursor.fetchall():
>     print row.keys()
> 
> What I get is:
> 
> ['league', 'BB', 'HR', 'IP', 'K', 'H', 'player_id', 'ER']
> 
> Neither alphabetical nor the order in which they were specified in the
> query nor... any seeming order I can suss out. Any ideas? Thanks!

keys in a dict are not guaranteed to be in any specific order. It's not
specific to the MySQLdb cursor.

IIRC it's related to the hashes of the keys (but obviously not in
strictly increasing order). You definitely shouldn't rely on the
ordering (hence the need for an OrderedDict.

e.g. 

>>> a = ['league', 'BB', 'HR', 'IP', 'K', 'H', 'player_id', 'ER']
>>> for s in a:
...   print hash(s)
... 
-3369365635700083487
8448050754076166
9216055368083080
9344056137084361
9600028874
9216027721
1844482854915224472
8832053061079775




More information about the Python-list mailing list