Open In App

Merge Key Value Lists into Dictionary Python

Last Updated : 24 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Merge key value list
# Using zip() + loop + defaultdict()
from collections import defaultdict
 
# initializing lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
 
# printing original lists
print("The original list1 is : " + str(test_list1))
print("The original list2 is : " + str(test_list2))
 
# Using zip() + loop + defaultdict()
# Merge key value list
res = defaultdict(list)
for i, j in zip(test_list1, test_list2):
   res[i].append(j)
 
# printing result
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




# Python3 code to demonstrate working of
# Merge key value list
# Using itemgetter() + groupby() + zip()
from itertools import groupby
from operator import itemgetter
 
# initializing lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
 
# printing original lists
print("The original list1 is : " + str(test_list1))
print("The original list2 is : " + str(test_list2))
 
# Using itemgetter() + groupby() + zip()
# Merge key value list
res = {keys: [i for _, i in sub] for keys, sub in groupby(
        zip(test_list1, test_list2), key = itemgetter(0))}
 
# printing result
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']
 
# Using dict comprehension
res = {key: [test_list2[i] for i in range(len(test_list1)) if test_list1[i] == key] for key in set(test_list1)}
 
# printing result
print("The merged key value dictionary is : " + str(res))
 
#This code is contributed by Edula Vinay Kumar Reddy


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




# Using for loop and setdefault method of dictionary
res = {}
# Input lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
# Printing original lists
print("The original list1 is :", test_list1)
print("The original list2 is :", test_list2)
# Merging key value list
for key, value in zip(test_list1, test_list2):
    res.setdefault(key, []).append(value)
# Printing result
print("The merged key value dictionary is :", res)
#This contributed by Jyothi pinjala.


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: 

  1. Import the itertools module.
  2. Use the groupby function from the itertools module to group the elements of the two lists based on the values of the first list.
  3. 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.
  4. Use a lambda function to specify the key for grouping in groupby, which will be the first element of each tuple.
  5. For each group of tuples with the same key, create a list of the second elements of each tuple using a list comprehension.
  6. 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.
  7. Assign the resulting dictionary to the variable res.
  8. Print the resulting dictionary.

Below is the implementation of the above approach:

Python3




import itertools
 
# initializing lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
 
# using itertools.groupby()
res = {key: [value[1] for value in group] for key, group in itertools.groupby(zip(test_list1, test_list2), key=lambda x: x[0])}
 
# printing result
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

  1. Convert input lists test_list1 and test_list2 to NumPy arrays arr1 and arr2.
  2. 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.
  3. 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.
  4. Print the resulting dictionary.

Python3




import numpy as np
from itertools import groupby
 
# Input lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
# Printing original lists
print("The original list1 is :", test_list1)
print("The original list2 is :", test_list2)
# Convert input lists to NumPy arrays
arr1 = np.array(test_list1)
arr2 = np.array(test_list2)
 
# Sort the arrays based on the values in arr1
sort_indices = np.argsort(arr1)
arr1 = arr1[sort_indices]
arr2 = arr2[sort_indices]
 
# Group the elements of arr2 based on the values in arr1
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 the resulting dictionary
print(grouped)
#This code is contributed by Rayudu.


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads