36

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rohita Khatiwada
  • 2,835
  • 9
  • 40
  • 52
  • 8
    You dictionary isn't an ordered dict -- it's an unordered plain Python dict. – Sven Marnach Aug 01 '11 at 11:31
  • 9
    Just because you call it ordered dict doesn't make it one! – Jacob Aug 01 '11 at 11:32
  • I know that this is an old question now, but what the previous 2 commentors are trying to say is that there is a class called OrderedDict in the collections module which you need to use if you want your dict to preserve order. Its also good to follow the python naming convention where classes are in CamelCase and variables in snake_case, so your variable should be ordered_dict (i.e. no capitalization of the first character). – Stephen Ellwood Jul 22 '19 at 14:26

3 Answers3

66

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
Matt
  • 3
  • 3
Michał Bentkowski
  • 2,115
  • 16
  • 10
  • 34
    `list(d.keys()).index('animal')` for anyone using **Python3** ending up here. – Torxed Feb 24 '14 at 17:21
  • 6
    It seems that simply using `list(d).index('animal')` also works in Python 3, unless I am missing something. –  May 31 '16 at 20:41
6

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).

Amnon Harel
  • 103
  • 1
  • 3
  • Note that this also works in Python 2 (tuple(d) just iterates over the keys of the dictionary and produces a tuple) – Tom Close Sep 05 '17 at 00:17
3

Think first that you need to read documentation. If you open a Python tutorial and then try to find information about OrderedDict you will see the following:

class collections.OrderedDict([items]) - Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

New in version 2.7.

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:

from collections import OrderedDict
d = OrderedDict((("fruit", "banana"), ("drinks", "water"), ("animal", "cat")))
d.keys()
>>> ['fruit', 'drinks', 'animal']
d.values()
>>> ['banana', 'water', 'cat']
# So
d.values().index('cat')
>>> 2
# Here is lambda
getPos = lambda oDict, toFind, byKey=True: list(oDict.keys() if byKey else oDict.values()).index(toFind)
# Now you can do the following
>>> getPos(d, 'animal')
>>> 2
>>> getPos(d, 'cat', False)
>>> 2
>>> getPos(d, 'water', False)
>>> 1
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52