python 中的字典,其顺序是我在开始时设置的

发布于 2024-10-08 07:41:58 字数 317 浏览 1 评论 0原文

我正在制作字典:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

但是当我显示它时,我发现这个字典被颠倒了。

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

怎样才能逆转回来呢?

或者,如果字典确实不可排序,我必须使用什么来收集信息顺序很重要的集合?

I'm making dictionary:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

But when I display it I saw that this dict is reversed.

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

﹉夏雨初晴づ 2024-10-15 07:41:58
from collections import OrderedDict

d = OrderedDict()
d["server"] = "mpilgrim"
d["database"] = "master"
d['mynewkey'] = 'mynewvalue'

print(d)

OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
from collections import OrderedDict

d = OrderedDict()
d["server"] = "mpilgrim"
d["database"] = "master"
d['mynewkey'] = 'mynewvalue'

print(d)

OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
祁梦 2024-10-15 07:41:58

字典是无序的(顺序是确定的,但取决于一些您甚至没有想到也不应该关心的因素 - 键的散列、插入顺序、冲突等)。在 Python 2.7+ 中,使用collections.OrderedDict。如果您必须使用旧版本,谷歌可以为您提供各种实现。

Dictionary are unordered (the order is deterministic, but depends on a handful of factors you don't even think of and shouldn't care about - hash of the keys, order of insertion, collisions, etc). In Python 2.7+, use collections.OrderedDict. If you must use an older version, there are various implementations google can point you to.

无所谓啦 2024-10-15 07:41:58

如果您使用的是 python 3.6,字典现在按插入顺序

https://www. python.org/dev/peps/pep-0468/

否则(正如其他人所说)我会推荐 collections.OrderedDict

If you are using python 3.6 dictionaries are now ordered by insertion order

https://www.python.org/dev/peps/pep-0468/

Otherwise (as other people have said) I would recommend collections.OrderedDict

恏ㄋ傷疤忘ㄋ疼 2024-10-15 07:41:58

您的词典尚未完全恢复。它部分根据您的键的哈希值进行排序。您无法更改此顺序(如果不使用自定义词典则无法更改)。在 python 2.7 或更高版本中,您可以使用有序字典 (collections.OrderedDict)。

在早期版本中,您可以使用以下食谱

另请看看这个问题:What is the bestordered dict implementation in python?

Your dictionnary is not quite reverted. It is sorted partly according to the hash of you keys. You can't change this order (not without using a custom dictionary). In python 2.7 or later you can use an ordered dictionary (collections.OrderedDict).

In earlier version you can use the following recipe.

Also have a look at this question : What is the best ordered dict implementation in python?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文