How to get position of key in a dictionary in python

gweno10 picture gweno10 · Mar 18, 2016 · Viewed 36.2k times · Source

If a key is present in a dictionary, I want to know what position the key is in i.e the numerical index. For example :

if the dictionary consists of :

{'test':{1,3},'test2':{2},'test3':{2,3}}

if 'test' in dictionary:
   print(the index of that key)

The output would be 0 for example. (The output would be 2 for 'test3'...)

I'm using a dictionary at the moment, I'm guessing I'd have to use an ordered dict to do this, but how can I do it using an ordered dict ?

Thanks for any help.

Answer

Aaron Christiansen picture Aaron Christiansen · Mar 18, 2016

For Python <3.6, you cannot do this because dictionaries in Python have no order to them, so items don't have an index. You could use an OrderedDict from the collections library instead though, and pass it a tuple of tuples:

>>> import collections
>>> d = collections.OrderedDict((('test',{1,3}),('test2',{2}),('test3',{2,3})))
>>> d.keys().index('test3') # Replace with list(d.keys()).index("test3") for Python 3
2