Can internal dictionary order change?

亡梦爱人 提交于 2019-12-20 01:00:09

问题


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

The above dictionary initially iterated through in this order:

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

Then, I moved around a ton of files in my code, and now it iterates through in this order:

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

I know that the order is internally stored as a hashmap, but what would cause that internal order to change?

Edit: I don't need to preserve order so I will stick with using a dict. I am just wondering why it happened. I thought order wasn't guaranteed, but once it has its arbitrary internal order, it sticks with it for future iterations.


回答1:


Dict don't have a fixed order, from documentation

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.

If you really need to keep it ordered, there is an object called OrderedDict :

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

see also OrderedDict documentation here




回答2:


Curious about why you want them ordered. Any chance it's just for consistent logging/printing or similar? If so, you can sort the keys alphabetically. See other article: How to sort dictionary by key in numerical order Python




回答3:


Yes. If you do change the code between different calls to the dict, the order of iteration will change.

From the docs

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

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



来源:https://stackoverflow.com/questions/38975722/can-internal-dictionary-order-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!