Open In App

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 = [6, 6, 6, 6], test_list2 = [8, 3, 2, 9] 
Output : {6: [8, 3, 2, 9]} 
Explanation : All mapped to single number.

Method #1 : Using zip() + loop

This is one of the ways in which this task can be performed. In this, we perform mapping the keys to required values using zip() and loop is used to perform iteration of keys.






# Python3 code to demonstrate working of
# Convert Lists into Similar key value lists
# Using loop + zip()
 
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# creating a mesh of keys with empty values list
res = {key: [] for key in test_list1}
 
# loop to iterate through keys and values
for key, val in zip(test_list1, test_list2):
    res[key].append(val)
 
# printing result
print("The mapped dictionary : " + str(res))

Output
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

Time Complexity: O(n*n) where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list 

Method #2 : Using defaultdict() + list comprehension + zip()

The combination of above functions can be used to solve this problem. In this, we perform task as one liner and defaultdict() is used to preassign values with empty lists.




# Python3 code to demonstrate working of
# Convert Lists into Similar key value lists
# Using defaultdict() + list comprehension + zip()
from collections import defaultdict
 
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# creating a mesh of keys using defaultdict
res = defaultdict(list)
[res[key].append(val) for key, val in zip(test_list1, test_list2)]
 
# printing result
print("The mapped dictionary : " + str(dict(res)))

Output
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

Method#3: Using Recursive method.

Algorithm:

  1. If keys is empty, return the result dictionary.
  2. Extract the first key-value pair from keys and values.
  3. If the key is already in the result dictionary, append the value to the list associated with the key. Otherwise, create a newlist with the value and add it to the dictionary with the key.
  4. Recursively call convert_lists_to_dict with the remaining key-value pairs in keys and values and the updated result dictionary.
  5. Return the result of the recursive call.




def convert_lists_to_dict(keys, values, result={}):
    if not keys:
        return result
     
    key = keys[0]
    value = values[0]
     
    if key in result:
        result[key].append(value)
    else:
        result[key] = [value]
     
    return convert_lists_to_dict(keys[1:], values[1:], result)
 
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# calling the function to get the resulting dictionary
result = convert_lists_to_dict(test_list1, test_list2)
 
# printing result
print("The mapped dictionary : " + str(result))
#this code contributed by tvsk

Output
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

The time complexity of this algorithm is O(n), where n is the length of the keys and values lists. This is because the function processes each key-value pair exactly once and performs a constant amount of work for each pair.

The auxiliary space complexity of the algorithm is O(k), where k is the number of unique keys in the keys list. This is because the function creates a list for each unique key in the keys list, and the size of each list is proportional to the number of occurrences of the key in the keys list. The result dictionary also requires O(k) space to store the keys and lists. In the worst case where all the keys in keys are unique, the space complexity is O(n).

Method #4: Using defaultdict() + enumerate() + list comprehension

Here’s a step-by-step approach to the code, along with the time and space complexity:

  1. Initialize two lists test_list1 and test_list2.
  2. Print the original lists.
  3. Create a defaultdict object res using the collections module. This object will have a default value of an empty list.
  4. Use list comprehension and zip() to iterate over test_list1 and test_list2 simultaneously, and for each element key in test_list1 and each corresponding element val in test_list2, append val to the list at the key key in the res defaultdict.
  5. Print the mapped dictionary res.




# Python3 code to demonstrate working of
# Convert Lists into Similar key value lists
# Using defaultdict() + enumerate() + list comprehension
 
from collections import defaultdict
 
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# creating a mesh of keys using defaultdict and enumerate
res = defaultdict(list)
[res[test_list1[i]].append(test_list2[i]) for i in range(len(test_list1))]
 
# printing result
print("The mapped dictionary : " + str(dict(res)))
#This code is contributed by Vinay Pinjala.

Output
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

Time complexity: The time complexity of this code is O(n), where n is the length of test_list1 or test_list2. This is because the code iterates through each element of the lists exactly once.
Auxiliary Space: The space complexity of this code is also O(n), where n is the length of test_list1 or test_list2. This is because the defaultdict object res will have at most n keys, and each key will have a list of values whose length is at most n.

Method #5: Using dictionary comprehension and zip()

Use a dictionary comprehension along with the built-in zip function to achieve the same result as the previous methods.

Step-by-step approach:




# Python3 code to demonstrate working of
# Convert Lists into Similar key value lists
# Using loop + zip()
 
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# creating a mesh of keys with empty values list
res = {key: [] for key in test_list1}
 
# loop to iterate through keys and values
for key, val in zip(test_list1, test_list2):
    res[key].append(val)
 
# printing result
print("The mapped dictionary : " + str(res))

Output
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

Time Complexity: O(n), where n is the length of the input lists, due to the iteration over the list of tuples.
Auxiliary Space: O(n), where n is the length of the input lists, due to the space required to store the dictionary.

Method #6: Using itertools.groupby() and dictionary comprehension

Step-by-Step Approach:

Below is the implementation of the above approach:




# importing the itertools module
import itertools
 
# initializing the lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# sorting the two lists in parallel and assigning the result to a new tuple
sorted_lists = sorted(zip(test_list1, test_list2))
 
# creating a dictionary comprehension using itertools.groupby()
res = {key: [val for _, val in group] for key, group in itertools.groupby(sorted_lists, key=lambda x: x[0])}
 
# printing the mapped dictionary
print("The mapped dictionary: " + str(res))

Output
The mapped dictionary: {4: [9], 5: [8, 10], 6: [2, 3, 4]}

Time complexity: O(n log n)
Auxiliary space: O(n) for the dictionary created with dictionary comprehension

Method #7: Using numpy:

Algorithm:

  1. Import the numpy module.
  2. Initialize two lists named test_list1 and test_list2 with integer values.
  3. Combine the two lists into a two-dimensional array using numpy’s array() method and transpose the matrix using T attribute to make the first column unique.
  4. Get the unique values of the first column using numpy’s unique() method and store them in a variable named unique_vals.
  5. Create an empty dictionary named res.
  6. For each value in unique_vals, perform the following:
    a. Use numpy’s where() method to get the indices where the first column is equal to the current value.
    b. Use numpy’s slicing operation to get the corresponding values from the second column.
    c. Convert the resulting numpy array into a list.
    d. Add the current value and its corresponding list to the res dictionary.
  7. Print the mapped dictionary.




import numpy as np
 
# initializing the lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# combining the two lists into a 2D array using NumPy
arr = np.array([test_list1, test_list2]).T
 
# getting the unique values of the first column using NumPy's unique() method
unique_vals = np.unique(arr[:, 0])
 
# creating a dictionary comprehension using NumPy's where() method
res = {val: list(arr[np.where(arr[:, 0] == val)][:, 1]) for val in unique_vals}
 
# printing the mapped dictionary
print("The mapped dictionary: " + str(res))
#This code is contributed by Jyothi pinjala.

Output:

The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary: {4: [9], 5: [8, 10], 6: [3, 2, 4]}
 

Time Complexity:

Initializing the lists and combining them into a 2D array takes O(n) time, where n is the length of the lists.
Getting the unique values using numpy’s unique() method takes O(n log n) time in the worst case.
Creating the dictionary comprehension takes O(n^2) time in the worst case because for each unique value, it needs to search for the corresponding values in the 2D array.
Printing the dictionary takes O(n) time because it needs to iterate through all n keys and values.
Therefore, the overall time complexity of the algorithm is O(n^2) in the worst case.

Space Complexity:

The space required to store the two lists is O(n).
The space required to store the 2D array is also O(n).
The space required to store the unique values of the first column is O(k), where k is the number of unique values.
The space required to store the dictionary is O(kn), where k is the number of unique values and n is the average length of the corresponding lists.
There are no other significant variables used in the algorithm.
Therefore, the overall space complexity of the algorithm is O(kn).

Method #8 : Using nested for loops + list(),set() methods

Approach

  1. Remove duplicates from test_list1 using list(),set() and store it in x, create an empty dictionary res
  2. Use nested for loops to initialise dictionary res with keys as values of x and values as the elements corresponding to the keys in test_list2
  3. Display res




# Python3 code to demonstrate working of
# Convert Lists into Similar key value lists
 
# initializing lists
test_list1 = [5, 6, 6, 4, 5, 6]
test_list2 = [8, 3, 2, 9, 10, 4]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# creating a mesh of keys with empty values list
res=dict()
 
# loop to iterate through keys and values
x=list(set(test_list1))
for i in x:
    z=[]
    for j in range(0,len(test_list1)):
        if(i==test_list1[j]):
            z.append(test_list2[j])
    res[i]=z
             
# printing result
print("The mapped dictionary : " + str(res))

Output
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {4: [9], 5: [8, 10], 6: [3, 2, 4]}

Time Complexity : O(M * N) M -length of x N – length of test_list2

Auxiliary Space : O(N) N – length of res dictionary


Article Tags :