Get the index of a Key in a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 15, 2022

banner

Photo from Unsplash

Get the index of a Key in a Dictionary in Python #

To get the index of a key in a dictionary:

  1. Use the list() class to convert the dictionary to a list of keys.
  2. Use the list.index() method to get the position of the key in the dictionary.
  3. The list.index() method will return the index of the specified key.
main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1 key = list(my_dict)[1] print(key) # 👉️ name value = list(my_dict.values())[1] print(value) # 👉️ Bobbyhadz

We used the list() class to convert the dictionary to a list of keys.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } print(list(my_dict)) # 👉️ ['id', 'name', 'age'] print(list(my_dict.keys())) # 👉️ ['id', 'name', 'age']

We could have also used the dict.keys() method to be more explicit.

The dict.keys method returns a new view of the dictionary's keys.

The last step is to use the list.index() method to get the position of the key in the dictionary.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1
The list.index() method returns the index of the first item whose value is equal to the provided argument.

The method raises a ValueError if there is no such item in the list.

We used an if statement to check if the key exists in the dictionary, so the list.index() method will never throw a ValueError.

You can use the index to get the key and value at the specific position.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1 key = list(my_dict)[index] print(key) # 👉️ name value = list(my_dict.values())[index] print(value) # 👉️ Bobbyhadz

To get the key at the specific position, we just have to convert the dictionary to a list of keys and access the list at the index.

To get the value, we convert the dict.values() view to a list and access it at the index.

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'bobbyhadz'} print(my_dict.values()) # 👉️ dict_values([1, 'bobbyhadz'])

If you need to get the position of multiple keys in the dictionary, use a for loop.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } keys = ['name', 'age'] for key in keys: if key in my_dict: # name - 1 # age - 2 print(f'{key} - {list(my_dict).index(key)}')

On each iteration, we check if the key is contained in the dictionary and print the corresponding index.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.