Python | Initializing dictionary with list index values
Last Updated :
22 Apr, 2023
While working with dictionaries, we might come across a problem in which we require to attach each value in list with it's index, to be used afterwards to solve question. This technique is usually very useful in competitive programming domain. Let's discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehension and enumerate() The combo of above methods can achieve this task. In this, enumerate()'s inbuilt capability to iterate value with it's index is used to construct a key to corresponding value using dictionary comprehension.
Python3
# Python3 code to demonstrate working of
# Initializing dictionary with index value
# Using dictionary comprehension and enumerate()
# Initialize list
test_list = ['gfg', 'is', 'best', 'for', 'CS']
# Printing original list
print("The original list is : " + str(test_list))
# using dictionary comprehension and enumerate()
# Initializing dictionary with index value
res = {key: val for val, key in enumerate(test_list)}
# printing result
print("Constructed dictionary with index value : " + str(res))
Output : The original list is : ['gfg', 'is', 'best', 'for', 'CS']
Constructed dictionary with index value : {'gfg': 0, 'is': 1, 'best': 2, 'CS': 4, 'for': 3}
Time complexity: O(n), where n is the length of the input list 'test_list'.
Auxiliary space: O(n), as we are creating a dictionary with n key-value pairs.
Method #2 : Using zip() + dict() + range() + len() This task can also be performed by nesting the above functions. The task performed above by enumerate is handles by range and len functions and zip and dict perform the task of binding key with value and dictionary conversion respectively.
Python3
# Python3 code to demonstrate working of
# Initializing dictionary with index value
# Using zip() + dict() + range() + len()
# Initialize list
test_list = ['gfg', 'is', 'best', 'for', 'CS']
# Printing original list
print("The original list is : " + str(test_list))
# using zip() + dict() + range() + len()
# Initializing dictionary with index value
res = dict(zip(test_list, range(len(test_list))))
# printing result
print("Constructed dictionary with index value : " + str(res))
Output : The original list is : ['gfg', 'is', 'best', 'for', 'CS']
Constructed dictionary with index value : {'gfg': 0, 'is': 1, 'best': 2, 'CS': 4, 'for': 3}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using a iteration and dict.update()
Python3
# Python3 code to demonstrate working of
# Initializing dictionary with index value
# Using dict.update()
# Initialize list
test_list = ['gfg', 'is', 'best', 'for', 'CS']
# Printing original list
print("The original list is : " + str(test_list))
# Initializing empty dictionary
res = {}
# Using dict.update()
for i in range(len(test_list)):
res.update({test_list[i]: i})
# printing result
print("Constructed dictionary with index value : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'CS']
Constructed dictionary with index value : {'gfg': 0, 'is': 1, 'best': 2, 'for': 3, 'CS': 4}
The above code snippet creates an empty dictionary, then uses a for loop to iterate over the range of the length of the input list. For each iteration, it updates the dictionary by adding the current element of the list as the key and the current index as the value, using the dict.update() method.
Time Complexity: O(n) where n is the number of elements in the list, as we are iterating through the list once
Auxiliary Space: O(n) as we are creating a new dictionary with n key-value pairs.
Method #4 : Using for loop
Python3
# Python3 code to demonstrate working of
# Initializing dictionary with index value
# Initialize list
test_list = ['gfg', 'is', 'best', 'for', 'CS']
# Printing original list
print("The original list is : " + str(test_list))
# Initializing dictionary with index value
res=dict()
for i in range(0,len(test_list)):
res[test_list[i]]=i
# printing result
print("Constructed dictionary with index value : " + str(res))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'CS']
Constructed dictionary with index value : {'gfg': 0, 'is': 1, 'best': 2, 'for': 3, 'CS': 4}
Time Complexity: O(n) where n is the number of elements in the list, as we are iterating through the list once
Auxiliary Space: O(n) as we are creating a new dictionary with n key-value pairs.
Method #6: Using map() and dict() functions in Python
This method uses the map() function to generate a sequence of index values and the dict() function to create a dictionary with index values.
Step-by-step approach:
Initialize a list test_list.
Use the enumerate() function to generate a sequence of index-value pairs from test_list.
Use the map() function with reversed() to swap the order of each index-value pair.
Use the dict() function to create a dictionary with the index-value pairs.
Store the result in a dictionary res.
Print the result.
Python3
# Initialize list
test_list = ['gfg', 'is', 'best', 'for', 'CS']
# Using map() and dict() functions
res = dict(map(reversed, enumerate(test_list)))
# Print the result
print("Constructed dictionary with index value : " + str(res))
OutputConstructed dictionary with index value : {'gfg': 0, 'is': 1, 'best': 2, 'for': 3, 'CS': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Python | Initializing dictionary with list index-values
While working with Python we might need to perform tasks in which we need to assign a dictionary with list values as dictionary values and index as dictionary keys. This type of problem is quite common in cases we need to perform data-type conversion. Let's discuss certain ways in which this task ca
4 min read
Python - Initialize dictionary with custom value list
In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with a custom list.
4 min read
Python | Initialize dictionary with None values
Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
4 min read
Initialize Python Dictionary with Keys and Values
In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize
3 min read
Python | Initialize list with empty dictionaries
While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it's utility in web development to store records. Let's discuss certain ways in which this task can be performed. Method #1 : Using {} + "*" operator Thi
5 min read
Python | Initialize dictionary with common value
While working with Python, sometimes, we might have a problem in which we require the initialize the static list into a dictionary with a constant value. Let's discuss certain ways in which this task can be performed. Method #1: Using dict() + list comprehension The combination of above functions ca
5 min read
Python - Dictionary with Index as Value
We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}.Using Dictionary ComprehensionWe can use dictionary comprehens
2 min read
Python | Grouping list values into dictionary
Sometimes, while working with data, we can be encountered a situation in which we have a list of lists and we need to group its 2nd index with the common initial element in lists. Let's discuss ways in which this problem can be solved. Method 1: Using defaultdict() + loop + dict() The defaultdict ca
7 min read
Python - Custom dictionary initialization in list
While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom dictionaries. This task has itâs utility in web development to store records. Letâs discuss certain ways in which this task can be performed. Method #1 : Using {dict} + "*" operato
3 min read
Python - Incremental value initialization in Dictionary
The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index incremental with K
5 min read