How to know the position of items in a Python ordered dictionary

Rohita Khatiwada picture Rohita Khatiwada · Aug 1, 2011 · Viewed 43.3k times · Source

Can we know the position of items in Python's ordered dictionary?

For example:

If I have dictionary:

// Ordered_dict is OrderedDictionary

Ordered_dict = {"fruit": "banana", "drinks": "water", "animal": "cat"}

Now how do I know in which position cat belongs to? Is it possible to get an answer like:

position (Ordered_dict["animal"]) = 2 ? or in some other way?

Answer

Michał Bentkowski picture Michał Bentkowski · Aug 1, 2011

You may get a list of keys with the keys property:

In [20]: d=OrderedDict((("fruit", "banana"), ("drinks", 'water'), ("animal", "cat")))

In [21]: d.keys().index('animal')
Out[21]: 2

Better performance could be achieved with the use of iterkeys() though.

For those using Python 3:

>>> list(d.keys()).index('animal')
2