在python中的字典与我在开始设置的顺序 [英] Dictionary in python with order I set at start

查看:663
本文介绍了在python中的字典与我在开始设置的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作字典:

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

如何逆向?

或者如果字典是不可排序的,我必须使用的集合,其中的信息的顺序是重要的?

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?

推荐答案

字典是无序的(顺序是确定性的,但取决于一些你甚至不想和不应该关心的因素 - 键的散列,插入顺序,碰撞等)。在Python 2.7+中,使用 collections.OrderedDict 。如果您必须使用旧版本,那么google可以指向您的各种实现。

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.

这篇关于在python中的字典与我在开始设置的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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