Python:按顺序检索字典键是否已添加?

Kaw*_*awu 3 python sorting dictionary key

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

String.compareMethods = {'equals': String.equals,
                         'contains': String.contains,
                         'startswith': String.startswith,
                         'endswith': String.endswith}
Run Code Online (Sandbox Code Playgroud)

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

有没有办法没有保持一个单独的列表(并没有为我正在尝试做的事情过度复杂)?对于我所看到的,由于涉及散列而不可能......

我正在使用Python 2.6.x.

agf*_*agf 9

使用collections.OrderedDictPython 2.7+,或OrderedDictPyPI用于旧版本的Python.您应该可以使用pip install ordereddict或安装Python 2.4-2.6 easy_install ordereddict.

它是一个子类dict,所以任何采用一个dictwill的方法也会接受一个OrderedDict.