Open In App

Python – Convert Lists into Similar key value lists

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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




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

Python3




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




# 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:

  • Define the two lists to be used as test_list1 and test_list2.
  • Use the “zip” function to combine the two lists into a list of tuples.
  • Create a dictionary using dictionary comprehension that iterates over the list of tuples.
  • For each tuple in the list, extract the first value as the key and the second value as the value to be appended to the list of values for that key.
  • If the key already exists in the dictionary, append the new value to the existing list of values for that key.
  • If the key does not exist in the dictionary, create a new key-value pair with the key and a list containing the value.
  • Print the resultant dictionary.

Python3




# 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:

  • Import the itertools module to use the groupby function.
  • Initialize the lists ‘test_list1‘ and ‘test_list2‘ with values.
  • Sort the two lists in parallel, using zip and sorted functions, and assign the result to a new tuple.
  • Create a dictionary comprehension that iterates over the groups generated by itertools.groupby().
  • For each group, set the key to the first element of the group and the value to the list of second elements of the group.
  • Print the mapped dictionary.

Below is the implementation of the above approach:

Python3




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

Python3




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




# 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



Similar Reads

Merge Key Value Lists into Dictionary Python
Sometimes, while working with lists, we can come forward with a problem in which we need to perform the merge function in which we have the key list and need to create dictionary mapping keys with corresponding value in other list. Let's discuss certain ways in which this task can be performed. Merge Key Value Lists into Dictionary Python Using zip
8 min read
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
Python | Convert key-value pair comma separated string into dictionary
Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task. Method #1: Using dictionary comprehension
5 min read
Python - Elements with K lists similar index value
Sometimes, while working with data, we can have a problem in which we need to get elements which are similar in K lists in particular index. This can have application in many domains such as day-day and other domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop This is brute way in which this task c
5 min read
Python program to convert a list into a list of lists using a step value
Given a List, the task here is to write a python program that can split the list into list of lists using by a step value here denoted via K. Input : test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8], K = 3Output : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]Explanation : 5, 2 and 9 are 0th, 3rd and 6th element respectively, and hence ( difference 3 ) grouped togethe
4 min read
Python - Filter key's value from other key
Sometimes, while working with Python dictionary, we can have a problem in which we need to extract a value from dictionary list of the key on basis of some other key equality. This kind of problem is common in domains that include data, for e.g web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [{'g
7 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python | Tuples with maximum key of similar values
Sometimes, while working with Python, we can have a problem in which we need to get all the records. This data can have similar values and we need to find maximum key-value pair. This kind of problem can occur while working with data. Let's discuss certain ways in which this task can be done. Method #1: Using max() + groupby() + itemgetter() + list
6 min read
Python - Append Similar Values as Key
Sometimes, while working with data, we can have problems in which we need to categorize a particular list and values to similar keys. This can be a problem in counting data. Like counting votes or counting coins. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is the brute way in which this task can be per
7 min read
Python - Extract Similar Key Values
Given a dictionary, extract all values which are from similar keys, i.e contains all similar characters, just jumbled to form each other. Input : test_dict = {'gfg' : 5, 'ggf' : 19, 'gffg' : 9, 'gff' : 3, 'fgg' : 3}, tst_wrd = 'fgg' Output : [5, 19, 3] Explanation : gfg, ggf and fgg have values, 5, 19 and 3.Input : test_dict = {'gfg' : 5, 'gffg' :
5 min read