close

How to get position of key in a dictionary in python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get position of key in a dictionary in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get position of key in a dictionary in python?

  1. How to get position of key in a dictionary in python?

    For Python <3.6, you cannot do this because dictionaries in Python have no order to them, so items don't have an index.

  2. get position of key in a dictionary in python

    For Python <3.6, you cannot do this because dictionaries in Python have no order to them, so items don't have an index.

Method 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

Method 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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read