Python program to Convert a list into a dictionary with index as key
We are given a list and our task is to convert it into a dictionary where each element’s index in the list becomes the key and the element itself becomes the corresponding value. For example, if we have a list like: ['apple', 'banana', 'cherry'] then the output will be {0: 'apple', 1: 'banana', 2: 'cherry'}.
Using enumerate()
enumerate() function allows us to get both the index and value from the list simultaneously and makes this a simple and efficient way to create a dictionary where the index is the key.
li = ['aryan', 'harsh', 'kunal']
res = dict(enumerate(li))
print(res)
Output
{0: 'apple', 1: 'banana', 2: 'cherry'}
Explanation: enumerate(li) generates pairs like (0, 'apple'), (1, 'banana'), (2, 'cherry') abnd dict() converts these pairs into a dictionary
Using a Dictionary Comprehension
This method uses dictionary comprehension to iterate over the list and create key-value pairs where the index becomes the key and the element is the value.
li = ['aryan', 'harsh', 'kunal']
res = {i: li[i] for i in range(len(li))}
print(res)
Output
{0: 'aryan', 1: 'harsh', 2: 'kunal'}
Explanation: {i: li[i] for i in range(len(li))} creates key-value pairs where the key is the index i and the value is the corresponding element li[i].
Using zip() with range()
zip() function can be used to combine two iterables: one for the indices (range(len(li))) and the other for the list values (li). This creates pairs of indices and elements which can then be converted into a dictionary.
li = ['aryan', 'harsh', 'kunal']
res = dict(zip(range(len(li)), li))
print(res)
Output
{0: 'aryan', 1: 'harsh', 2: 'kunal'}
Explanation of Code:
zip(range(len(li)), li)pairs each index inrange(len(li))with the corresponding element inli.dict()converts these pairs into a dictionary.
Using a for Loop
We can also use a simple for loop to iterate through the list and add key-value pairs to an empty dictionary.
li = ['aryan', 'harsh', 'kunal']
res = {}
for i in range(len(li)):
res[i] = li[i]
print(res)
Output
{0: 'aryan', 1: 'harsh', 2: 'kunal'}
Explanation: for loop iterates over the indices of the list and each index is used as a key in the dictionary with the corresponding list element as the value.