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 type dict;

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

I get this:

 a b g 

it looks like python is sorting the dict automatically! How can I get the original unsorted list?

Gough

+4
source share
5 answers

Dictations do not work like this:

CPython implementation details . Keys and values ​​are listed in random order, which is nonrandom, varies in different Python implementations, and depends on the history of inserting and deleting dictionaries.

Instead, you can use a list with 2 roots:

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

A similar but better solution is described in the Wayne answer .

+11
source

As already mentioned, dicts does not order or order the elements you insert. This is β€œmagic” as to how it is ordered when it is received. If you want to keep the order sorted or not, you also need to bind a list or tuple.

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

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

Just change [] to () if you don't need to change the original list / order.

+10
source

Do not use a dictionary. Or use the Python 2.7 / 3.1 OrderedDict .

+6
source

No dictionaries in dictionaries, no original unsorted list.

+2
source

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

CPython implementation details: Keys and values ​​are listed in an arbitrary order, which is not accidental, varies through the Python implementation and depends on the history of the insert and delete dictionaries.

+1
source

Source: https://habr.com/ru/post/1311204/


All Articles