gath
gath

Reputation: 25462

How to print unsorted dictionary in python?

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

Upvotes: 5

Views: 25886

Answers (5)

Skilldrick
Skilldrick

Reputation: 70819

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.

Upvotes: 11

Wayne Werner
Wayne Werner

Reputation: 51807

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.

Upvotes: 11

unbeli
unbeli

Reputation: 30228

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.

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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

Upvotes: 6

SilentGhost
SilentGhost

Reputation: 319561

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

Upvotes: 2

Related Questions