Wednesday, July 3, 2024
HomeLanguagesPythonPython – Convert Lists of List to Dictionary

Python – Convert Lists of List to Dictionary

Sometimes, while working with Python records, we can have problem in which we have data in form of Lists of list 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. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using loop This is brute way in which we perform this task. In this, we iterate through the lists forming key value pairs according to required slicing. 

Python3




# Python3 code to demonstrate working of
# Convert Lists of List to Dictionary
# Using loop
 
# 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 : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}

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”.

  Method #2 : Using dictionary comprehension This is yet another way in which this task can be performed. This is similar to above method, just a one liner alternative. 

Python3




# Python3 code to demonstrate working of
# Convert Lists of List to Dictionary
# Using dictionary comprehension
 
# 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 : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}

Time Complexity: O(n), where n is the length of the input list. This is because we’re using the dictionary comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #3 : Using dictionary+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)

Method 4 : Using the zip() function and a loop to iterate over the nested lists.

 step-by-step approach:

  1. Initialize an empty dictionary result_dict.
  2. Use the zip() function to create a list of tuples from the nested lists. The zip() function will group elements from each sublist by their positions in the list, creating tuples of elements at the same position.
  3. For example, zip([‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4]) will create the list [(‘a’, ‘c’), (‘b’, ‘d’), (1, 3), (2, 4)].
  4. Use a loop to iterate over the tuples from the zip() function. For each tuple, use the first two elements as the key for the dictionary and the remaining elements as the value.
  5. Add the key-value pair to the result_dict.
  6. Return result_dict.

Python3




# Python3 code to demonstrate working of
# Convert Lists of List to Dictionary
# Using zip() and loop
 
# 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)}

The time complexity of this approach is O(nm), where n is the number of sublists in the list and m is the length of the sublists. 

The auxiliary space is also O(nm), since we need to store the dictionary and tuples.

Method #5: Using the reduce() function

Step-by-step approach:

  1. We start by importing the reduce() function from the functools library.
  2. We initialize a list called test_list that contains three nested lists. Each nested list contains four elements: two strings and two integers.
  3. We print the original list using the print() function.
  4. We define a function called combine_dicts that takes two dictionaries as its arguments and merges them into a single dictionary using the update() method.
  5. We use the reduce() function to apply the combine_dicts function to all of the nested dictionaries in the test_list.
  6. We print the mapped dictionary using the print() function

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.

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments