【问题标题】:Python: retrieve dictionary keys in order as added?Python:按添加顺序检索字典键?
【发布时间】:2012-03-30 02:51:38
【问题描述】:

在 Python 中,有没有办法按照添加项目的顺序检索键列表?

String.compareMethods = {'equals': String.equals,
                         'contains': String.contains,
                         'startswith': String.startswith,
                         'endswith': String.endswith}

您在此处看到的键用于选择(下拉)框,因此顺序很重要。

有没有办法不保留单独的列表(并且不会使我想做的事情过于复杂)?据我所知,由于涉及哈希,这是不可能的......

我使用的是 Python 2.6.x。

【问题讨论】:

    标签: python sorting dictionary key


    【解决方案1】:

    在 Python 2.7+ 上使用 collections.OrderedDict,在旧版本的 Python 上使用 OrderedDict from PyPI。您应该可以使用pip install ordereddicteasy_install ordereddict 为Python 2.4-2.6 安装它。

    它是dict 的子类,因此任何采用dict 的方法也将接受OrderedDict

    【讨论】:

    • 所以,只有添加自定义字典的方法。我不像大多数人那样处于通常的 Python 环境中,所以我必须检查这对我来说是否属于“过于复杂的事情”。
    • @Kawu 这是一个单一的班级。请参阅code.activestate.com/recipes/576693,该软件包所基于的配方。如果需要,您可以简单地将其复制粘贴到现有模块中——这并不复杂。
    • 当然可以,但这有点粗糙。我可能不得不这样做,因为我无法预见该脚本运行的版本。否则我必须检查版本,然后使用一些条件逻辑来使用 Python 提供的 OrderedDict 如果在 2.7+ 环境中或回退到我提供的实现。不知道这是否可能,我也不知道这是否可取。
    • @Kawu try: from collections import OrderedDictexcept: import OrderedDict # or your entire implementation here
    【解决方案2】:

    你需要的是OrderedDict

    from collections import OrderedDict
    
    d = OrderedDict();
    d['equals'] = String.equals
    d['contains'] = String.contains
    # ...
    

    【讨论】:

    • 是的,但他使用的是 Python 2.6,所以没有 collections.OrderedDict
    • 没错,这就是我添加额外信息的原因。
    猜你喜欢
    • 2013-03-07
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2022-01-23
    • 2023-03-04
    相关资源
    最近更新 更多