How to get position of key in a dictionary in python

50,146

Solution 1

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

Solution 2

As of Python 3.6, dictionaries now preserves the insertion order. So using Python 3.6+, you could get the index by converting the dict_keys to a list.

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

if 'test' in dictionary:
   print(list(dictionary).index('test'))

As another example, the following demonstrates how to find the index for a few keys of interest.

key_list = list(dictionary)
keys_of_interest = ['test2', 'test3']

for key in keys_of_interest:
    print('key: {}, index: {}'.format(key, key_list.index(key)))

The output from this would be

key: test2, index: 1
key: test3, index: 2

Solution 3

You can just build an index :

ind= {k:i for i,k in enumerate(dictionary.keys())}

then ind['test3'] will be 2, with O(1) access time.

This is robust while keys are fixed. If you add/remove keys, you have to rebuild the index.

Solution 4

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

Solution 5

Unfortunately, such a thing is not possible because of how dictionaries are constructed in python. These data structures are inherently unordered.

To get the functionallity you want you must use a different data structure, such as OrderedDict

Share:
50,146
gweno10
Author by

gweno10

Updated on July 09, 2022

Comments

  • gweno10
    gweno10 almost 2 years

    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.