Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 662
gath Avatar asked Nov 28 '22 08:11

gath


1 Answers

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.

like image 149
Skilldrick Avatar answered Dec 09 '22 18:12

Skilldrick