Can an internal dictionary reorder?

exampleDict = {'a':1, 'b':2, 'c':3, 'd':4}

The above dictionary was initially repeated in the following order:

b=2
d=4
a=1
c=3

Then I moved about a thousand files to my code, and now iterates in the following order:

d=4
a=1
c=3
b=2

I know that order is internally stored as hashmap, but what can cause a change in internal order?

Edit: I don't need to keep order, so I will stick with using dict. I'm just wondering why this happened. I thought order was not guaranteed, but as soon as it has its own arbitrary internal order, it sticks to it for future iterations.

+4
source share
3 answers

Dict ,

CPython: , , Python .

, OrderedDict:

from collections import OrderedDict
exampleDict = OrderedDict({'a':1, 'b':2, 'c':3, 'd':4})

. OrderedDict

+5

, , . , / ? , . . : Python

0

Yes. If you change the code between different calls in a dict, the iteration order will change.

From docs

If elements (), keys (), values ​​(), iteritems (), iterkeys () and itervalues ​​() are called without intermediate changes to the dictionary, the lists will correspond directly.

If the insertion order of matter, check out the OrderedDict class

-1
source

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


All Articles