Python: extract dictionary keys in order of addition?

In Python, is there a way to get the list of keys in the order in which the elements were added?

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


The keys you see here are for selecting a (dropdown) field, so the order is important.

Is there a way without keeping a separate list (and without overdoing it for what I'm trying to do)? For what I can see, this is not possible due to hashing ...

I am using Python 2.6.x.


source to share

2 answers

Use collections.OrderedDict

on Python 2.7+ or OrderedDict

from PyPI
for older Python versions. You have to install it for Python 2.4-2.6 using pip install ordereddict

or easy_install ordereddict


It is a subclass dict

, so any method that accepts dict

will also accept OrderedDict




What you need is called OrderedDict .

from collections import OrderedDict

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




All Articles