How to get position of key in a dictionary in python

Viewed 61928

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.

6 Answers

With python 3.6 or later, with dicts preserving insertion order, then you can do it in one line, with it returning 'None' if the key isn't in the dictionary:

key_index = list(my_dictionary).index(the_key) if the_key in my_dictionary else None

You can just convert dict.keys() to a list and then index the list

keys = list(dictionary.keys())
index = keys.index("test")

indexing values that are not in the list will result in ValueError

keys.index("test5")
ValueError: "test5" is not in list
Related