Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Dictionary with index as value

Python | Dictionary with index as value

The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kinds of problems with their solutions. This article deals with yet another similar type of problem of converting a list to a dictionary, with values as the index where the element occurs. Let’s discuss specific ways in which this problem can be solved. 

Example

Input: ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
Output: {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}
Explaiantion: Converting a list to a dictionary with indexes as values

Convert a List to a Dictionary with Index as Values in Python

In Python, a dictionary is a data structure that stores the elements in key-value pairs. There are many ways to convert a Python list into a dictionary with the list index as the dictionary’s values. Let us see a few methods.

  • Using Dictionary Comprehension
  • Using dict() + zip()
  • Using index() + For Loop
  • Using a For Loop and Counter Variable
  • Using map() Function and Lambda Function
  • Using Dictionary Comprehension + range()
  • Using reduce() Function
  • Using NumPy

Using Dictionary Comprehension + Enumerate()

This problem can be solved easily using the combination of the above functions. In Python, dictionary comprehension can perform the task of constructing the dictionary, and enumerate() function can be used to access the index value along with the element. 

Python3




# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
 
# printing original list
print("The original list : " + str(test_list))
 
# using Dictionary comprehension + enumerate()
# Dictionary with index as value
res = {val: idx + 1 for idx, val in enumerate(test_list)}
 
# print result
print("The Dictionary after index keys : " + str(res))


Output:

The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}

Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(n), where n is the number of elements in the list.

Using dict() + zip()

This problem can also be solved using the combination of the above functions. The dict() method can be used to convert to the dictionary and the zip() function can be used to map the indices with the keys. 

Python3




# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
 
# printing original list
print("The original list : " + str(test_list))
 
# using dict() + zip()
# Dictionary with index as value
res = dict(zip(test_list, range(1, len(test_list)+1)))
 
# print result
print("The Dictionary after index keys : " + str(res))


Output:

The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}

Time Complexity: O(n) where n is the number of elements in the list.
Auxiliary Space: O(n) where n is the number of elements in the dictionary.

Using index() + For Loop

In this method, we will use the for loop to iterate over each element of the list. Then by using the list index() function, we will get the index value of each element and store it in the dictionary in Python.

Python3




# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
 
# printing original list
print("The original list : " + str(test_list))
res = dict()
for i in test_list:
    res[i] = test_list.index(i)+1
 
# print result
print("The Dictionary after index keys : " + str(res))


Output:

The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}

Time complexity: O(n^2) where n is the number of elements in the list.
Auxiliary space: O(n) where n is the number of elements in the dictionary.

Using a For Loop and Counter Variable

This method uses a for loop and a counter variable to construct the dictionary in Python. The counter variable is incremented at each iteration of the loop, and its value is used as the value in the dictionary for the current element.

Python3




def list_to_dict(lst):
    # Initialize empty dictionary
    res = {}
    # Initialize counter variable
    counter = 1
    # Iterate through elements in the list
    for x in lst:
        # Assign counter as the value for the current element
        res[x] = counter
        # Increment counter
        counter += 1
    # Print the original list
    print("Original list:", lst)
    # Return the modified dictionary
    return res
 
 
print("The Dictionary after index keys :", list_to_dict(
    ['Nikhil', 'Akshat', 'Akash', 'Manjeet']))


Output:

Original list: ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}


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.

Using map() Function and Lambda Function

In this method, we used the enumerate() on the list to get values and indexes and then use the lambda function that returns a tuple with (value, index+1). Then the map() function is used to apply the lambda function to each tuple in the list. The resulting map object is then converted to a dictionary using the dict() constructor.

Python3




# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
 
# printing original list
print("The original list : " + str(test_list))
 
# using map() function and lambda function
# Dictionary with index as value
res = dict(map(lambda x: (x[1], x[0]+1), enumerate(test_list)))
 
# print result
print("The Dictionary after index keys : " + str(res))


The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}


Time complexity: O(n)
Auxiliary space: O(n)

Using Dictionary Comprehension + range()

In this approach, we will be using dictionary comprehension and the range() method to iterate the element of the list.

Python3




# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
 
# printing original list
print("The original list : " + str(test_list))
 
# using dictionary comprehension + range()
# Dictionary with index as value
res = {test_list[i]:i+1 for i in range(len(test_list))}
 
# print result
print("The Dictionary after index keys : " + str(res))


Output:

The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3, 'Manjeet': 4}

Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(n), as we are creating a dictionary with n key-value pairs.

Using reduce() Function

In this method, we will use the reduce() from the functools module to convert a list to a dictionary in Python. We will create a lambda function that takes two arguments: acc (accumulator) which is an empty dictionary and cur (current element). Then use enumerate() function to create a sequence of (index, element) pairs from the test_list starting from index 1.

In each iteration, a new key-value pair is added to the accumulator dictionary where the key is the index and the value is the element. Then the result of reduce() function is stored in a variable named res.

Python3




from functools import reduce
 
# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
 
# printing original list
print("The original list : " + str(test_list))
 
# using reduce()
# Dictionary with index as value
res = reduce(lambda acc, cur: {
             **acc, cur[0]: cur[1]}, enumerate(test_list, start=1), {})
 
# print result
print("The Dictionary after index keys : " + str(res))
# This code is contributed by Rayudu.


Output:

The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] 
The Dictionary after index keys : {1: 'Nikhil', 2: 'Akshat', 3: 'Akash', 4: 'Manjeet'}


Time complexity: O(n), where n is the length of the input list.

Space complexity: O(n), where n is the length of the input list.

Using NumPy

This approach uses the NumPy library to create a dictionary with index as a value. The np.arange() function is used to create an array of indices and then np.column_stack() is used to stack the indices and original list element into a single 2D array. Finally, a dictionary is created using the first column of the 2D array as keys and the second column as values.

Python3




# Importing NumPy library
import numpy as np
 
# Defining a function to convert list to dictionary
 
def list_to_dict(test_list):
 
    # Creating NumPy array of indices
    # using np.arange() function
    idx = np.arange(1, len(test_list)+1)
 
    # Stacking the original list and the array
    # of indices using np.column_stack() function
    arr = np.column_stack((test_list, idx))
 
    # Creating dictionary using first column of the
    # 2D array as keys and second column as values
    res = {arr[i][0]: arr[i][1] for i in range(len(arr))}
 
    # Returning the dictionary
    return res
 
 
# Test
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
print("The original list : " + str(test_list))
 
# Function call
res = list_to_dict(test_list)
 
# Printing the resultant dictionary
print("The Dictionary after index keys : " + str(res))


Output:

The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': '1', 'Akshat': '2', 'Akash': '3', 'Manjeet': '4'}


Time Complexity: O(n), where n is the number of elements in the list.

Auxiliary Space: O(n), where n is the number of elements in the list.

RELATED ARTICLES

Most Popular

Recent Comments