views:

203

answers:

5

Guys,

I have this dict in python;

d={}
d['b']='beta'
d['g']='gamma'
d['a']='alpha'

when i print the dict;

for k,v in d.items():
    print k

i get this;

a
b
g

it seems like python sorts the dict automatically! how can i get the original unsorted list?

Gath

+7  A: 

Dicts don't work like that:

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

You could use a list with 2-tuples instead:

d = [('b', 'beta'), ('g', 'gamma'), ('a', 'alpha')]

A similar but better solution is outlined in Wayne's answer.

Skilldrick
+2  A: 

There is no order in dictionaries to speak of, there is no original unsorted list.

SilentGhost
As Marcelo Cantos mentions, newer versions of Python provide OrderedDict, which preserves insertion order.
John Y
@John: as OP mentions he's using built-in `dict`
SilentGhost
+4  A: 

Don't use a dictionary. Or use the Python 2.7/3.1 OrderedDict type.

Marcelo Cantos
+1  A: 

No, python does not sort dict, it would be too expensive. The order of items() is arbitrary. From python docs:

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

unbeli
+3  A: 

As has been mentioned, dicts don't order or unorder the items you put in. It's "magic" as to how it's ordered when you retrieve it. If you want to keep an order -sorted or not- you need to also bind a list or tuple.

This will give you the same dict result with a list that retains order:

greek = ['beta', 'gamma', 'alpha']
d = {}
for x in greek:
    d[x[0]] = x

Simply change [] to () if you have no need to change the original list/order.

Wayne Werner
+1 This is a crafy solution :)
Skilldrick