我如何信任Python字典的顺序?

oro*_*aki 1 python dictionary

我正在尝试在Python中创建一个我可以排序的字典,但是当我添加新内容时它似乎会改变顺序.有没有解决的办法?

Mit*_*eat 9

标准词典不会强加排序,它只是一个查找.

你想要一个有序字典有序字典.

  • 请注意,Python 3.1和最终的Python 2.7包含这样一个类:http://docs.python.org/dev/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections (2认同)

Ale*_*lli 5

Python dict被构建为哈希表 - 性能很好,但排序本质上是任意的,不可预测的.如果您需要偶尔进行可预测排序的步行,并且基于键或值,则sorted内置非常方便:

# print all entries in sorted key order
for k in sorted(d): print k, d[k]

# print all entries in reverse-sorted value order
for k in sorted(d, key=d.get, reverse=True): print k, d[k]

# given all keys are strings, print in case-insensitive sorted order
for k in sorted(d, key=str.lower): print k, d[k]
Run Code Online (Sandbox Code Playgroud)

等等.如果您需要不同(例如,跟踪插入密钥的相应时间,或者更改其值,等等),其他答案中建议的"有序词典"将更好地为您服务(但从未使用过令人敬畏的原始数据)表现真实dict! - ).