【问题标题】:Should dict store key in order by inc?dict 是否应该按 inc 顺序存储密钥?
【发布时间】:2011-07-21 11:56:23
【问题描述】:

我有一个以整数为键的字典。请告诉我,字典是否使用排序键存储数据?

我写了一点代码来测试(如下):

>>> 
>>> d = {1: 'a', 3: 'a'}
>>> d
{1: 'a', 3: 'a'}
>>> d[2] = 'a'
>>> d
{1: 'a', 2: 'a', 3: 'a'}
>>> 

但我不确定这种行为是否标准且始终有效。

【问题讨论】:

标签: python


【解决方案1】:

python 中的字典没有排序。在此处阅读有关 dicts 的更多信息: http://docs.python.org/library/stdtypes.html?highlight=dict#dict

但您可以使用sorted python built-in method 对键进行排序:

for k in sorted(myDict):
    myDict[k] # do something

或在此处查找collections.OrderedDict implementation

您还可以混合使用 sorted 方法和 OrderedDict 以供以后使用(确保这只会在您不向其中添加新项目的情况下使用 - 否则使用 sorted 方法会更好):

d = {1: 'a', 3: 'a'}   
from collections import OrderedDict   
sorted_d = OrderedDict((k, d[k]) for k in sorted(d))

【讨论】:

  • 请注意,OrderedDict 所做的只是跟踪插入键的顺序。与保持键排序非常不同。
【解决方案2】:

多做一点实验很快就会发现它们没有排序:

>>> d = {1: 'a', 3: 'a', 8: 'a'}
>>> d
{8: 'a', 1: 'a', 3: 'a'}

但即使这样也取决于实现。完全不依赖顺序。

【讨论】:

    【解决方案3】:

    内部字典不保留键的排序顺序。如果您想要 C python 的快速 C 实现,请查看 sorteddict,它包含在我的 CPython 的 ordereddict 包中: http://anthon.home.xs4all.nl/Python/ordereddict/

    【讨论】:

    • 有人知道 sorteddict 的纯 python 实现吗?
    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多