4
votes

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

5

5 Answers

11
votes

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.

11
votes

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.

6
votes

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

2
votes

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

1
votes

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.