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
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'CS' ]
print ("The original list is : " + str (test_list))
res = {key: val for val, key in enumerate (test_list)}
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
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'CS' ]
print ("The original list is : " + str (test_list))
res = dict ( zip (test_list, range ( len (test_list))))
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
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'CS' ]
print ( "The original list is : " + str (test_list))
res = {}
for i in range ( len (test_list)):
res.update({test_list[i]: i})
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, '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
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'CS' ]
print ( "The original list is : " + str (test_list))
res = dict ()
for i in range ( 0 , len (test_list)):
res[test_list[i]] = i
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, '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
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'CS' ]
res = dict ( map ( reversed , enumerate (test_list)))
print ( "Constructed dictionary with index value : " + str (res))
|
Output
Constructed 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 Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read