Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 915
Kawu Avatar asked Sep 26 '26 00:09

Kawu


1 Answers

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.

like image 187
agf Avatar answered Sep 28 '26 12:09

agf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!