Open In App

Python – Convert Lists of List to Dictionary

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python records, we can have a problem in which we have data in the form of Lists of lists and we need to allocate certain elements as keys and certain as values to form a dictionary. This type of application can occur in data domains. Let’s discuss certain ways in which this task can be performed. 

Convert Lists of List to Dictionary in Python

Below are the ways by which we can convert lists of list to a Dictionary in Python:

  • Using Loop
  • Using Dictionary Comprehension
  • Using dictionary and tuple()
  • Using the zip() function and a loop
  • Using reduce() function

Convert Lists of List to Dictionary in Python Using Loop

This is the brute way in which we perform this task. In this, we iterate through the lists forming key value pairs according to require slicing. In this example, the Python code converts a list of lists (test_list) into a dictionary (res) using a loop, with the first two elements of each sublist as keys and the remaining elements as values.

Python3




# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Lists of List to Dictionary
# Using loop
res = dict()
for sub in test_list:
    res[tuple(sub[:2])] = tuple(sub[2:])
 
# printing result
print("The mapped Dictionary : " + str(res))


Output

The original list is : [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
The mapped Dictionary : {('a', 'b'): (1, 2), ('c', 'd'): (3, 4), ('e', 'f'): (5, 6)}

Time Complexity: O(n) where n is the total number of values in the list “test_list”. 
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.

Python Convert Lists of List to Dictionary Using Dictionary Comprehension

In this example, the Python code converts a list of lists (test_list) into a dictionary (res) using dictionary comprehension, where the first two elements of each sublist serve as keys, and the remaining elements are used as values.

Python3




# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Lists of List to Dictionary
# Using dictionary comprehension
res = {tuple(sub[:2]): tuple(sub[2:]) for sub in test_list}
 
# printing result
print("The mapped Dictionary : " + str(res))


Output

The original list is : [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
The mapped Dictionary : {('a', 'b'): (1, 2), ('c', 'd'): (3, 4), ('e', 'f'): (5, 6)}

Time Complexity: O(n)
Auxiliary Space: O(n)

Python Convert Nested List into Dictionary Using Dictionary and tuple()

We use a dictionary comprehension to create a dictionary with key-value pairs. The key of each pair is a tuple containing the first two elements of the sublists in the original list, and the value is a tuple containing the remaining elements of the sublists. We use the tuple() function to convert a sublist to a tuple.

Python3




original_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
 
mapped_dict = {(lst[0], lst[1]): tuple(lst[2:]) for lst in original_list}
 
print("The mapped Dictionary :", mapped_dict)


Output

The mapped Dictionary : {('a', 'b'): (1, 2), ('c', 'd'): (3, 4), ('e', 'f'): (5, 6)}

Time Complexity:  O(n^2)
Auxiliary Space:  O(n)

Convert Nested List into Dictionary Using the zip() Function and a Loop

In this example, the Python code converts a list of lists (test_list) into a dictionary (result_dict) using a combination of the zip() function and a loop. The first two elements of each sublist are used as keys, and the remaining elements are combined into tuples and used as values

Python3




# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Lists of List to Dictionary
# Using zip() and loop
result_dict = {}
for sublist in test_list:
    key = tuple(sublist[:2])
    value = tuple(sublist[2:])
    result_dict[key] = value
 
# printing result
print("The mapped Dictionary : " + str(result_dict))


Output

The original list is : [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
The mapped Dictionary : {('a', 'b'): (1, 2), ('c', 'd'): (3, 4), ('e', 'f'): (5, 6)}

Time Complexity: O(nm), where n is the number of sublists in the list and m is the length of the sublists. 
Auxiliary Space: O(nm)

Convert Lists of List to Dictionary Using the reduce() Function

In this example, the Python code uses the functools.reduce() function to combine dictionaries generated from a list of lists (test_list). The combine_dicts function is defined to update and merge dictionaries, and the resulting combined dictionary (res) represents the conversion of the original list into a dictionary, where the first two elements of each sublist serve as keys, and the remaining elements are used as values.

Python3




from functools import reduce
 
# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
 
# printing original list
print("The original list is: " + str(test_list))
 
# define function to combine dictionaries
 
def combine_dicts(dict1, dict2):
    dict1.update(dict2)
    return dict1
 
# use reduce to apply combine_dicts to all nested dictionaries
res = reduce(combine_dicts, [
             {tuple(sub[:2]): tuple(sub[2:])} for sub in test_list])
 
# print mapped dictionary
print("The mapped dictionary: " + str(res))


Output

The original list is: [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
The mapped dictionary: {('a', 'b'): (1, 2), ('c', 'd'): (3, 4), ('e', 'f'): (5, 6)}

Time Complexity: O(n^2), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.



Similar Reads

Python - Convert Key-Value list Dictionary to List of Lists
Sometimes, while working with a Python dictionary, we can have a problem in which we need to perform the flattening of a key-value pair of dictionaries to a list and convert it to a list of lists. This can have applications in domains in which we have data. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + item
8 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 which this task can be performed. Input : test_list =
9 min read
Python | Convert list of tuples to dictionary value lists
One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st elements of tuple, which are uniquely identified as keys in dictionary and it's corresponding value as a list of the corresponding value of respective keys as tuple's second element. Let's discuss how to solve
9 min read
Python - Convert list of dictionaries to dictionary of lists
In this article, we will discuss how to convert a list of dictionaries to a dictionary of lists. Method 1: Using for loop By iterating based on the first key we can convert list of dict to dict of list. Python program to create student list of dictionaries C/C++ Code # create a list of dictionaries # with student data data = [ {'name': 'sravan', 's
3 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Python | Convert two lists into a dictionary
Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let's discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python. Converting Two Lists into a DictionaryPython List is a sequence dat
9 min read
Python - Convert Strings to Uppercase in Dictionary value lists
Given dictionary with values list, convert all the strings to upper case. Input : {"Gfg" : ["ab", "cd"], "Best" : ["gh"], "is" : ["kl"]} Output : {'Gfg': ['AB', 'CD'], 'Best': ['GH'], 'is': ['KL']} Explanation : All value lists strings are converted to upper case. Input : {"Gfg" : ["ab", "cd", "Ef"]} Output : {'Gfg': ['AB', 'CD', "EF"]} Explanation
8 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
three90RightbarBannerImg