How to access a Dictionary Key by Index in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Get the index of a Key in a Dictionary and access the key
  2. Accessing Dictionary keys or values by Index
  3. Accessing dictionary values by key
  4. Accessing Dictionary Items by Index
  5. Accessing Dictionary keys or values by Index with enumerate()
  6. Getting all dictionary keys that have a specific value

# Get the index of a Key in a Dictionary and access the key

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

get index of key in dictionary

The code for this article is available on GitHub

Once we find the index of the key in a dictionary, we have to convert the dictionary to a list to access it.

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 code for this article is available on GitHub
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.

# Accessing Dictionary keys or values by Index

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

access dictionary keys or values by index

The code for this article is available on GitHub

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'])

# Accessing dictionary values by key

Note that unless you have a good reason to access the keys and values in the dictionary using an index, using bracket notation is much more performant.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'address': { 'country': 'Chile' }, 'tasks': ['dev', 'test'] } print(my_dict['name']) # ๐Ÿ‘‰๏ธ Bobbyhadz print(my_dict['address']) # ๐Ÿ‘‰๏ธ {'country': 'Chile'} print(my_dict['address']['country']) # ๐Ÿ‘‰๏ธ Chile print(my_dict['tasks'][0]) # ๐Ÿ‘‰๏ธ dev

accessing dictionary values by key

The code for this article is available on GitHub

You can specify a key between the square brackets to access the corresponding value.

# Accessing Dictionary Items by Index

You can also use the dict.items() method to get a dictionary key-value pair by index.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = 1 key, value = list(my_dict.items())[index] print(key) # ๐Ÿ‘‰๏ธ name print(value) # ๐Ÿ‘‰๏ธ Bobbyhadz

access dictionary items by index

The code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } # ๐Ÿ‘‡๏ธ dict_items([('id', 1), ('name', 'Bobbyhadz'), ('age', 30)]) print(my_dict.items())

The dict_items object is not subscriptable (cannot be accessed at an index), so we used the list() class to convert it to a list.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = 1 key, value = list(my_dict.items())[index] print(key) # ๐Ÿ‘‰๏ธ name print(value) # ๐Ÿ‘‰๏ธ Bobbyhadz

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(a_list) - 1.

# Getting the index of multiple keys in a dictionary

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)}')
The code for this article is available on GitHub

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

# Accessing Dictionary keys or values by Index with enumerate()

You can also use the enumerate() function to access dictionary keys or values by index.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = 1 key = next( key for idx, key in enumerate(my_dict) if idx == index ) print(key) # ๐Ÿ‘‰๏ธ name # ------------------------------------------------------ value = next( value for idx, value in enumerate(my_dict.values()) if idx == index ) print(value) # ๐Ÿ‘‰๏ธ Bobbyhadz
The code for this article is available on GitHub

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } for index, key in enumerate(my_dict): # 0 id # 1 name # 2 age print(index, key)

On each iteration, we check if the current index is equal to the specified index and return the corresponding key or value.

# Getting all dictionary keys that have a specific value

If you need to get all dictionary keys that have a specific value, use a list comprehension.

main.py
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'salary': 30, } keys = [key for key, value in my_dict.items() if value == 30] print(keys) # ๐Ÿ‘‰๏ธ ['age', 'salary']
The code for this article is available on GitHub

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current value is equal to 30 and return the result.

The keys list only stores the keys of the items that have a value of 30.

# Using the OrderedDict class instead

As of Python 3.7, the standard dict class is guaranteed to preserve the insertion order of keys.

You can check your version of python by issuing the python --version command.

shell
python --version

If you use an older version (than 3.7), use the OrderedDict class instead.

main.py
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'Bobbyhadz'), ('age', 30)] ) key = list(my_dict)[1] print(key) # ๐Ÿ‘‰๏ธ name value = list(my_dict.values())[1] print(value) # ๐Ÿ‘‰๏ธ Bobbyhadz index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # ๐Ÿ‘‰๏ธ 1
The code for this article is available on GitHub

The list() class can also be used to convert the keys of an OrderedDict to a list.

Note that using the OrderedDict class is only necessary if you use a version older than Python 3.7.

Otherwise, use the native dict class as it preserves insertion order.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev