Kawu
Kawu

Reputation: 14003

Python: retrieve dictionary keys in order as added?

In Python, is there a way to retrieve the list of keys in the order in that the items were added?

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

The keys you see here are meant for a select (dropdown) box so the order is important.

Is there a way without keeping a separate list (and without overcomplicating things for what I'm trying to do)? For what I see it's not possible due to the hashing involved...

I'm using Python 2.6.x.

Upvotes: 3

Views: 3577

Answers (2)

agf
agf

Reputation: 176770

Use a collections.OrderedDict on Python 2.7+, or OrderedDict from PyPI for older versions of Python. You should be able to install it for Python 2.4-2.6 with pip install ordereddict or easy_install ordereddict.

It is a subclass of dict, so any method that takes a dict will also accept an OrderedDict.

Upvotes: 9

Adam Bard
Adam Bard

Reputation: 1713

What you need is called OrderedDict.

from collections import OrderedDict

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

Upvotes: 2

Related Questions