内部字典订单可以改变吗? [英] Can internal dictionary order change?

查看:122
本文介绍了内部字典订单可以改变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我知道该订单内部存储为一个hashmap,但是会导致内部订单更改?

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

编辑:我不需要保留订单,所以我会坚持使用dict。我只是想知道为什么会发生。我认为订单不能保证,但是一旦它有任意的内部订单,它会坚持使用它来进行以后的迭代。

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.

推荐答案

Dict没有固定的订单,从文档


Dict don't have a fixed order, from documentation


CPython实现细节:键和值以
任意顺序列出,这是非随机的,因Python而异
实现,并且取决于字典的插入历史
和删除。

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.

如果你真的需要保留它的排序,那里是一个名为 OrderedDict 的对象:

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})

另请参阅OrderedDict文档 here

see also OrderedDict documentation here

这篇关于内部字典订单可以改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆