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() + loop + defaultdict()
The combination of above method can be used to perform this particular task. In this, we use zip function to match the like elements of lists with each other and loop is then used to assign the keys with value from zipped list to add value to a defaultdict.
Python3
from collections import defaultdict
test_list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 ]
test_list2 = [ 'gfg' , 'is' , 'best' , 'Akash' , 'Akshat' , 'Nikhil' , 'apple' , 'grapes' ]
print ( "The original list1 is : " + str (test_list1))
print ( "The original list2 is : " + str (test_list2))
res = defaultdict( list )
for i, j in zip (test_list1, test_list2):
res[i].append(j)
print ( "The merged key value dictionary is : " + str ( dict (res)))
|
Output
The original list1 is : [0, 0, 0, 1, 1, 1, 2, 2]
The original list2 is : ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
The merged key value dictionary is : {0: ['gfg', 'is', 'best'], 1: ['Akash', 'Akshat', 'Nikhil'], 2: ['apple', 'grapes']}
Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the input lists. The defaultdict and result dictionary both take up additional space.
Merge Key Value Lists into Dictionary Using itemgetter() + groupby() + zip()
This is yet another way to perform this particular task. In this, we group the keys fetched by itemgetter to the first list with the elements of other list which is linked using the zip function using groupby method.
Python3
from itertools import groupby
from operator import itemgetter
test_list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 ]
test_list2 = [ 'gfg' , 'is' , 'best' , 'Akash' , 'Akshat' , 'Nikhil' , 'apple' , 'grapes' ]
print ( "The original list1 is : " + str (test_list1))
print ( "The original list2 is : " + str (test_list2))
res = {keys: [i for _, i in sub] for keys, sub in groupby(
zip (test_list1, test_list2), key = itemgetter( 0 ))}
print ( "The merged key value dictionary is : " + str ( dict (res)))
|
Output
The original list1 is : [0, 0, 0, 1, 1, 1, 2, 2]
The original list2 is : ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
The merged key value dictionary is : {0: ['gfg', 'is', 'best'], 1: ['Akash', 'Akshat', 'Nikhil'], 2: ['apple', 'grapes']}
Time complexity: O(nlogn), where n is the length of the input lists.
Auxiliary space: O(n), where n is the length of the input lists.
Merge Key Value Lists into Dictionary Using dictionary comprehension
This method uses dict comprehension to merge the key-value lists. It creates a new dictionary with keys from the first list and values as lists of corresponding values from the second list.
Python3
test_list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 ]
test_list2 = [ 'gfg' , 'is' , 'best' , 'Akash' , 'Akshat' , 'Nikhil' , 'apple' , 'grapes' ]
res = {key: [test_list2[i] for i in range ( len (test_list1)) if test_list1[i] = = key] for key in set (test_list1)}
print ( "The merged key value dictionary is : " + str (res))
|
Output
The merged key value dictionary is : {0: ['gfg', 'is', 'best'], 1: ['Akash', 'Akshat', 'Nikhil'], 2: ['apple', 'grapes']}
This method has time complexity of O(n) where n is the length of the first list and space complexity of O(n) since we are creating a new dictionary with keys from the first list and values as lists of corresponding values from the second list.
Merge Key Value Lists into Dictionary Using a for loop and setdefault method
Python3
res = {}
test_list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 ]
test_list2 = [ 'gfg' , 'is' , 'best' , 'Akash' , 'Akshat' , 'Nikhil' , 'apple' , 'grapes' ]
print ( "The original list1 is :" , test_list1)
print ( "The original list2 is :" , test_list2)
for key, value in zip (test_list1, test_list2):
res.setdefault(key, []).append(value)
print ( "The merged key value dictionary is :" , res)
|
Output
The original list1 is : [0, 0, 0, 1, 1, 1, 2, 2]
The original list2 is : ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
The merged key value dictionary is : {0: ['gfg', 'is', 'best'], 1: ['Akash', 'Akshat', 'Nikhil'], 2: ['apple', 'grapes']}
Time Complexity: O(N)
Auxiliary Space: O(N)
Merge Key Value Lists into Dictionary Using itertools.groupby()
This method involves using the groupby function from the itertools module to group the elements of the two lists based on the values of the first list. The groupby function returns an iterator that groups the adjacent elements with the same key. Then, we can use a dictionary comprehension to create the final dictionary.
Step-by-step approach:
- Import the itertools module.
- Use the groupby function from the itertools module to group the elements of the two lists based on the values of the first list.
- Use the zip function to create a list of tuples, where each tuple contains an element from test_list1 and test_list2 at the same index.
- Use a lambda function to specify the key for grouping in groupby, which will be the first element of each tuple.
- For each group of tuples with the same key, create a list of the second elements of each tuple using a list comprehension.
- Create a dictionary comprehension to create the final dictionary, where the keys are the unique values from test_list1, and the values are the lists created in step 6.
- Assign the resulting dictionary to the variable res.
- Print the resulting dictionary.
Below is the implementation of the above approach:
Python3
import itertools
test_list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 ]
test_list2 = [ 'gfg' , 'is' , 'best' , 'Akash' , 'Akshat' , 'Nikhil' , 'apple' , 'grapes' ]
res = {key: [value[ 1 ] for value in group] for key, group in itertools.groupby( zip (test_list1, test_list2), key = lambda x: x[ 0 ])}
print ( "The merged key value dictionary is : " + str (res))
|
Output
The merged key value dictionary is : {0: ['gfg', 'is', 'best'], 1: ['Akash', 'Akshat', 'Nikhil'], 2: ['apple', 'grapes']}
Time complexity: O(nlogn) where n is the length of the input lists due to the sorting operation in groupby.
Auxiliary space: O(n) for the dictionary and the list of values in each key.
Merge Key Value Lists into Dictionary Using numpy
- Convert input lists test_list1 and test_list2 to NumPy arrays arr1 and arr2.
- Sort the arrays arr1 and arr2 based on the values in arr1. To do this, we first obtain the indices that would sort arr1 using the argsort() method. We then use these indices to rearrange arr1 and arr2.
- Group the elements of arr2 based on the values in arr1. To do this, we use the groupby() function from the itertools module to group the indices of arr1 by their corresponding values, creating a dictionary where the keys are the values of arr1 and the values are lists of indices. We then use a dictionary comprehension to create a new dictionary where the keys are the values of arr1 and the values are the corresponding elements of arr2.
- Print the resulting dictionary.
Python3
import numpy as np
from itertools import groupby
test_list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 ]
test_list2 = [ 'gfg' , 'is' , 'best' , 'Akash' , 'Akshat' , 'Nikhil' , 'apple' , 'grapes' ]
print ( "The original list1 is :" , test_list1)
print ( "The original list2 is :" , test_list2)
arr1 = np.array(test_list1)
arr2 = np.array(test_list2)
sort_indices = np.argsort(arr1)
arr1 = arr1[sort_indices]
arr2 = arr2[sort_indices]
grouped = {k: list (g) for k, g in groupby( range ( len (arr1)), key = lambda x: arr1[x])}
grouped = {k: [arr2[i] for i in v] for k, v in grouped.items()}
print (grouped)
|
Output:
The original list1 is : [0, 0, 0, 1, 1, 1, 2, 2]
The original list2 is : ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
{0: ['gfg', 'is', 'best'], 1: ['Akash', 'Akshat', 'Nikhil'], 2: ['apple', 'grapes']}
The time complexity: O(n log n) due to the sorting step,
The auxiliary space : O(n) for the new NumPy arrays and the final dictionary.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Jun, 2023
Like Article
Save Article