Python - Convert List to Index and Value dictionary
Last Updated :
01 May, 2023
Given a List, convert it to dictionary, with separate keys for index and values.
Input : test_list = [3, 5, 7, 8, 2, 4, 9], idx, val = "1", "2"
Output : {'1': [0, 1, 2, 3, 4, 5, 6], '2': [3, 5, 7, 8, 2, 4, 9]}
Explanation : Index and values mapped at similar index in diff. keys., as "1" and "2".
Input : test_list = [3, 5, 7], idx, val = "1", "2"
Output : {'1': [0, 1, 2], '2': [3, 5, 7]}
Explanation : Index and values mapped at similar index in diff. keys., as "1" and "2".
Method : Using loop + enumerate()
In this, we iterate for list elements using enumerate() to get index along with values, and append the values and indices accordingly in separate dictionaries accordingly.
Python3
# Python3 code to demonstrate working of
# Convert List to Index and Value dictionary
# Using loop + enumerate()
# initializing list
test_list = [3, 5, 7, 8, 2, 4, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing keys for index and vals
idx, val = "indx", "vals"
# initializing empty mesh
res = {idx : [], val : []}
for id, vl in enumerate(test_list):
res[idx].append(id)
res[val].append(vl)
# printing results
print("Constructed dictionary : " + str(res))
OutputThe original list is : [3, 5, 7, 8, 2, 4, 9]
Constructed dictionary : {'indx': [0, 1, 2, 3, 4, 5, 6], 'vals': [3, 5, 7, 8, 2, 4, 9]}
Time Complexity: O(n), where n is the length of the dictionary
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary
Method 2: Using zip() and dictionary comprehension:
First uses zip() to create a list of tuples where each tuple contains an index-value pair. Then, it uses dictionary comprehension to convert the list of tuples to a dictionary with keys "indx" and "vals", where each key's value is a list of the corresponding indices or values. Finally, it prints the resulting dictionary.
Python3
test_list = [3, 5, 7, 8, 2, 4, 9]
# using zip() to create a list of tuples, where each tuple contains an index-value pair
pairs = list(zip(range(len(test_list)), test_list))
# using dictionary comprehension to convert the list of tuples to a dictionary with keys "indx" and "vals"
res = { "indx": [i for i, v in pairs], "vals": [v for i, v in pairs] }
# print the resulting dictionary
print(res)
Output{'indx': [0, 1, 2, 3, 4, 5, 6], 'vals': [3, 5, 7, 8, 2, 4, 9]}
Time Complexity: O(N), where N is the length of the input list.
Auxiliary Space: O(N)
Method 3: Use the built-in dict() constructor with a generator expression
Step-by-step approach:
- Creates a dictionary named result with two keys:
'indx': a list of the indices of the values in test_list, created using the range() function and the len() function to generate a list of integers from 0 to 6 (the length of test_list minus 1).
'vals': a reference to the original test_list. - Finally, the code prints the original list and the constructed dictionary
Python3
test_list = [3, 5, 7, 8, 2, 4, 9]
result = {'indx': list(range(len(test_list))), 'vals': test_list}
print("The original list is:", test_list)
print("Constructed dictionary:", result)
OutputThe original list is: [3, 5, 7, 8, 2, 4, 9]
Constructed dictionary: {'indx': [0, 1, 2, 3, 4, 5, 6], 'vals': [3, 5, 7, 8, 2, 4, 9]}
Time complexity: O(n), where n is the length of the list, because it only requires iterating over the list once to create the key-value pairs.
Auxiliary space: O(n), because the resulting dictionary will contain n key-value pairs.
Similar Reads
Python - Convert Index Dictionary to List
Sometimes, while working with Python dictionaries, we can have a problem in which we have keys mapped with values, where keys represent list index where value has to be placed. This kind of problem can have application in all data domains such as web development. Let's discuss certain ways in which
3 min read
Convert a Dictionary to a List in Python
In Python, dictionaries and lists are important data structures. Dictionaries hold pairs of keys and values, while lists are groups of elements arranged in a specific order. Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dict
3 min read
Python Convert Dictionary to List of Values
Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python - Convert dictionary items to values
Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let
3 min read
Convert a List to Dictionary Python
We are given a list we need to convert the list in dictionary. For example, we are given a list a=[10,20,30] we need to convert the list in dictionary so that the output should be a dictionary like {0: 10, 1: 20, 2: 30}. We can use methods like enumerate, zip to convert a list to dictionary in pytho
2 min read
Convert Matrix to Dictionary Value List - Python
We are given a matrix and the task is to map each column of a matrix to customized keys from a list. For example, given a matrix li = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]] and a list map_li = [4, 5, 6], the goal is to map the first column to the key 4, the second column to the key 5, and the
3 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in whi
9 min read
Convert List of Tuples to Dictionary Value Lists - Python
The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list.For example, given the list li = [(1, 'gfg'), (1, '
4 min read
Convert List to Single Dictionary Key - Value list - Python
We are given a list and a element K, our aim is to transform the given list into a dictionary where the specified element (Kth element) becomes the key and the rest of the elements form the value list. For example: if the given list is: [6, 5, 3, 2] and K = 1 then the output will be {5: [6, 3, 2]}.U
4 min read