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 to know in which position cat belongs to? Is it possible to get answer like:
position ( Ordered_dict["animal"]) = 2 ?
or in some other way ?
For Python3:
tuple(d).index('animal')
This is almost the same as Marein's answer above, but uses an immutable tuple instead of a mutable list. So it should run a little bit faster (~12% faster in my quick sanity check).
Think first that you need is to read documentation. If you open python tutorial and then try to find information about OrderedDict you will see the following:
So in case you are using an ordered dictionary and you are not going to delete keys - then 'animal' will be always in the position you add - e.g. index 2.
Also to get an index of a 'cat' you can simply use:
You may get list of keys with the
keys
property:A better performance could be achieved with the use of
iterkeys()
though.For those using Python 3