How To Access A Dictionary Key By Index In Python?

Dictionaries in Python offer efficient storage for key-value pairs. Unlike lists, dictionaries support non-unique keys, allowing for diverse data storage. This tutorial delves into various methods for accessing dictionary keys by index in the Python programming language. We explore the significance of this operation and provide practical examples to illustrate each approach

*Working on Jupyter Notebook Anaconda Environment. 

1. Instantiated The key as a list.

The keys are instantiated as a list to grab a Dictionary Key by index In Python. In order to display the keys view as a list, the keys view must be instantiated. 

The following example returns a list of keys from a menu object by calling the list(cuisines). [index] returns the key at index in fst_key, and index slicing structure to access a dictionary key-values in fst_value. 

The execution process goes in the following manner;

#simple dictionary with key-values
cuisines = {

  "dish01": "Thai",
  "dish02": "Moroccan",
  "dish03": ["Turkish"]

fst_key = list(cuisines)[2]

fst_val = list(cuisines.values())[2][0]

print("fst_key: ",fst_key)
print("fst_val: ", fst_val)
fst_key:  dish03
fst_val:  Turkish

2. By defining a function 

You can access a dictionary key by its index in Python by defining a function that utilizes a for-loop in conjunction with the enumerate function. Here’s an improved version of your explanation:

To access a dictionary key by index in Python, you can follow these steps:

  1. Define a function named “get_nth_key” using the “def” keyword.
  2. Specify a condition within an “if” statement to check if the provided key index is equal to the desired index, in this case, “2”.
  3. Utilize the len() function to determine the total number of keys/items in the dictionary.
  4. Access the keys of the dictionary using the “keys()” method.
  5. Include another condition within the function to check if it evaluates to true. If it does, the program proceeds to print the key.
  6. Return the key object to complete the function.
  7. Call the “get_nth_key” function, passing the “cuisines” dictionary as an argument, and store the returned key in the variable “fst_key”.
  8. Finally, create a variable “fst_val” to store the value associated with the key at index “2” in the “cuisines” dictionary.

Here’s the revised code and explanation:

#simple dictionary with key-values
cuisines = {
  "dish01": "Thai",
  "dish02": "Moroccan",
  "dish03": ["Turkish"]

def get_nth_key(cuisines, i=2):
    if i < 2:
        i += len(cuisines)
    for j, key in enumerate(cuisines.keys()):
         if j == i:
            return key
fst_key = get_nth_key(cuisines)
fst_val = cuisines[fst_key]

print("fst_key: ",fst_key)
print("fst_val: ", fst_val)
fst_key:  dish03
fst_val:  ['Turkish']

3. Using keys() to access dictionary keys by index

The keys() method can be used in conjunction with list indexing to access dictionary keys by index:

# a dictionary
flowers_dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}

dict_index_value = flowers_dict[list(flowers_dict.keys())[2]]

4. index() method to grab dictionary key by index

The index() method is employed to retrieve dictionary keys based on their index values. This process is exemplified through the following steps:

  1. Initialize a dictionary.
  2. Declare a variable without a value.
  3. Utilize the ‘if…in’ structure to check for the existence of a key in the dictionary.
  4. Upon finding a matching key, the method returns the index of that key.
  5. Capture the index using list() in conjunction with the original dictionary and its index location. Subsequently, this index can be used to print the key corresponding to that particular index.
  6. Alternatively, you can directly access the key by passing the index of the desired key within square brackets, for example, [2].

Here’s an illustration of the process:

flowers_dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}

flower_index = None
if 'passion flower' in flowers_dict:
   flower_index = list(flowers_dict).index('passion flower')

key = list(flowers_dict)[flower_index]
passion flower

5. Accessing key-Index with function using enumerate() function

The enumerate() function is used here to iterate through the dictionary keys and find the index of a specific key. Moreover, it helps to access a dictionary key and index both. Consider the setup of a dictionary:

flowers_dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}

We define a function that takes in two parameters: the original dictionary and the key whose index is to be accessed. The function is structured without list comprehension, in conjunction with the enumerate function.

def access_key_at_index(flowers_dict, accessing_key):
    for index, key in enumerate(flowers_dict.keys()):
        if key == accessing_key:
            return index

To utilize this function and retrieve the index for a specific key, simply call the function with the relevant key as the argument, like this:

access_key_at_index(flowers_dict, "passion flower")

6. Grab the dictionary key

To access a specific dictionary key in Python, you can index the dictionary in the following way. The process is similar to the previous example, with the specific aim of retrieving the dictionary key based on an index. In contrast to the previous case, we are now interested in retrieving the key based on its index.

In this specific dictionary, the key ‘water lily’ can be found at index 3. The enumeration process starts counting from 0.

Consider the following code snippet:

# a dictionary
flowers_dict = {'Red Ginger': 1, 'Tree Poppy': 2, 'passion flower': 3, 'water lily': 4}
def access_key_at_index(flowers_dict, accessing_index):

#enumerate read the dictionary in index order from 0,1,...
   for i_index, k_key in enumerate(flowers_dict.keys()):
#if index is equal to or match with the index to be access
#in function argument attribute it will returns the required key for that specific index
       if i_index == accessing_index:
           return k_key
#passing function attributes to its arguments
'water lily'

7. Access dictionary keys by index with an index-slicing approach

Here is the simple approach to accessing keys by their index using the index slicing approach. In the following example, from a dictionary, every key is individual access by slicing using braces.

info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan','Feb'],
         'year': '2023'}
access_key_by_index = list(info)


Do it in a more Pythonic way

A modified one-liner approach makes it more Pythonic to accomplish this task  to access the key by index, remember, converting Dictionary to list 

info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan','Feb'],
         'year': '2023'}

8. Access dictionary keys by index using the items() method

Items () reads the dictionary, and translates it to a tuple in a list. Here is how it works:

  • A dictionary generation
  • Using list() in aggregation with items() to convert a dictionary to a list containing tuples.
  • Now invoke braces to access the dictionary key and values.
  • The default items() returns the value for both key-values.
info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan','Feb'],
         'year': '2023'}
info = list(info.items())
#returns key-value both
#returns key 
#return value for a particular key
('year', '2023')

9. Using list comprehension to access dictionary key by index 

Using list comprehension one-liner structure in aggregation with items() method makes it easier to grab the dictionary key by its index in Python. However, Here is how it executes:

  • Considering a desired dictionary
  • Using list comprehension structure to perform the desired task
  • For…in structure, search the variable in the dictionary, and items() helps to find the required variable in the dictionary, where its value matches its corresponding value [‘Jan’,’Feb’].
  • Append [0] with list comprehension structure. It will delete [] and quotes from the desired results.
info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan','Feb'],
         'year': '2023'}
#list comprehension
info = [k for k, v in info.items() if v == ['Jan','Feb']]

info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan','Feb'],
         'year': '2023'}
# append [0] to remove braces
append_info = [k for k, v in info.items() if v == ['Jan','Feb']][0]

10. Dictionary  comprehension to access key by index

Dictionary comprehension is a one-liner syntax structure similar to list comprehension to perform the task and make it do the job in a more Pythonic way. Here dictionary comprehension is used in aggregation with the items() function to access the dictionary key by index in Python. 

Dictionary comprehension returns the output in the form of a dictionary format. However, list comprehension produces output in list format; in this case, we append [0] to remove the list format from the output. However, This way, we remove the brackets from the list or the opening and closing brackets from the output.

info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan','Feb'],
         'year': '2023'}
# Check for items 2023 in the dictionary
dict_key = {i:j for (i,j) in info.items() if j=='2023'}
{'year': '2023'}

Another way to use dict comprehension is to access a dictionary key by index in Python. 

In the following example, the dictionary key is accessed by index using dictionary comprehension. Then, the output variable is converted to a list and appended by [0] to remove the opening and closing brackets from the list. 

info = {'weekdays': ["Sunday", "Monday","Tuesday", "Thursday","Friday", "Saturday"],
         'month': ['Jan'],
         'year': '2023'}
dict_items  = {k for k, v in info.items() if v == ['Jan']}
#append zeo to remove list format ['']


This page will find different methods for grabbing a dictionary key in Python by index. Python provides several procedures for accessing key indexes in dictionaries. However, this page covers almost all the possible methods to access a dictionary key by index in Python. Use the one that best fits your problem.

If you want to learn more about Python Programming, visit Python Programming Tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *