Open In App

Python program to Convert a list into a dictionary with index as key

Last Updated : 27 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a python list, the task is to write a Python program to convert the list into a dictionary with indexes as keys.

Example:

Input – [‘Ramesh’, ‘Mahesh’, ‘Kamlesh’, ‘Suresh’]
Output – {0: ‘Ramesh’, 1: ‘Mahesh’, 2: ‘Kamlesh’, 3: ‘Suresh’}

Input – [‘Carrot’, ‘Raddish’, ‘Brinjal’, ‘Potato’]
Output – {0: ‘Carrot’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’}

Convert a list into a dictionary Using Dictionary Comprehensions

In this method without using any extra function, we will convert a list into a dictionary.

Python




def list_to_dict_with_index(lst):
    dict_with_index = {index: value for index, value in enumerate(lst)}
    return dict_with_index
 
if __name__ == "__main__":
    sample_list = ['a', 'b', 'c', 'd', 'e']
    result_dict = list_to_dict_with_index(sample_list)
    print(result_dict)


Output:

{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

Convert a list into a dictionary Using enumerates and a for loop.

In this method, we will enumerate the provided list and then use the index as a key and assign it to the corresponding value.

Python3




employee_names = ['Ramesh', 'Mahesh', 'Kamlesh', 'Suresh']
 
names_dict = {}
for i, name in enumerate(employee_names):
  names_dict[i] = name
 
print(names_dict)


Output

{0: 'Ramesh', 1: 'Mahesh', 2: 'Kamlesh', 3: 'Suresh'}

Time complexity: O(n), where n is the number of elements in the employee_names list. 
Auxiliary space: O(n), as the names_dict dictionary has to store one key-value pair for each element in the employee_names.

The above task can be done without using the for loop as shown below:

Python3




vegetables = ['Carrot', 'Raddish', 'Brinjal', 'Potato']
 
veg_dict = dict(enumerate(vegetables))
print(veg_dict)


Output

{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'}

Time complexity: O(n), where n is the number of elements in the vegetables list. 
Auxiliary space: O(n), where n is the number of elements in the vegetables list.

Convert a list into a dictionary Using the zip and range function

In this method, basically, we use lists of the values and the list of indexes that are created by using the range() function.

Python3




vegetables = ['Carrot', 'Raddish', 'Brinjal', 'Potato']
 
veg_dict = dict(zip(range(len(vegetables)), vegetables))
print(veg_dict)


Output

{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'}

Time complexity: O(n), where n is the length of the list ‘vegetables’.
Auxiliary space: O(n), as the dictionary ‘veg_dict’ created will have n key-value pairs, where n is the length of the list ‘vegetables’.

Convert a list into a dictionary using yield

Use the dict function and pass it a generator function that generates the tuples. This can be done using a generator function and the yield function.

  • Define a function called index_tuple_generator which takes a list as an argument.
  • Inside the function, use a for loop to iterate over the list using the enumerate() function, enumerate() returns an iterator that generates a tuple containing a count (from start, which defaults to 0) and the values obtained from iterating over the list.
  • For each iteration of the loop, create a tuple containing the index of the current element and the element itself.
  • Use the yield keyword to return the tuple from the function. yield is similar to return, but it allows the function to return a generator object instead of a regular value. This means that the function can be called multiple times to generate different values.
  • Create a list called lst containing some strings.
  • Call the index_tuple_generator() function with lst as an argument, and convert the generator object it returns into a dictionary using the dict() constructor.
  • Assign the resulting dictionary to a variable called dct.
  • Print the value of dct.

Python3




def index_tuple_generator(lst):
    for i, x in enumerate(lst):
        yield (i, x)
 
lst = ['Ramesh', 'Mahesh', 'Kamlesh', 'Suresh']
 
dct = dict(index_tuple_generator(lst))
print(dct)
#This code is contributed by Edula Vinay Kumar Reddy


Output

{0: 'Ramesh', 1: 'Mahesh', 2: 'Kamlesh', 3: 'Suresh'}

Time complexity: O(n) because it involves a single loop that iterates through all the elements in the input list.
Auxiliary Space: O(1) because it does not use any additional data structures and the space it uses is independent of the input size. The yield statement is used to generate the tuples one at a time, so the function does not need to store all the tuples in memory at once.

Convert a list into a dictionary Using list comprehension and the enumerate function.

Use a list comprehension and the built-in enumerate function to generate a list of tuples containing the index and element of each item in the input list. Then, the built-in dict function is used to convert the list of tuples into a dictionary.

Follow the below steps to implement the above idea:

  • Use a list comprehension and the enumerate function to create a list of tuples, where each tuple contains the index and element of each item in the input list. The syntax for the list comprehension is [(i, x) for i, x in enumerate(lst)].
  • Use the built-in dict function to convert the list of tuples into a dictionary.
  • Return the dictionary.

Below is the implementation of the above approach:

Python3




def index_tuple_generator(lst):
    return dict([(i, x) for i, x in enumerate(lst)])
 
lst = ['Ramesh', 'Mahesh', 'Kamlesh', 'Suresh']
dct = index_tuple_generator(lst)
print(dct)


Output

{0: 'Ramesh', 1: 'Mahesh', 2: 'Kamlesh', 3: 'Suresh'}

Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads