Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Last Updated : 04 Sep, 2022
Improve Article
Save Article

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

Let’s see our objective of this article by an 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’}

Method 1: Using Dictionary Comprehensions

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

Output:

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

Method 2: 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'}

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'}

Method 3: 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'}

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!