Merge Key Value Lists into Dictionary Python
Last Updated :
24 Jun, 2023
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.
Similar Reads
Python | List value merge in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we have many dictionaries and we are required to merge like keys. This problem seems common, but complex is if the values of keys are list and we need to add elements to list of like keys. Let's discuss way in which this prob
5 min read
Python - Key Value list pairings in Dictionary
Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be
7 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
2 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Python - Value limits to keys in Dictionaries List
Given a Dictionaries list, write a Python program to assign limits to each key in dictionary list.( each having all keys ). Examples: Input : test_list = [{"gfg" : 4, "is" : 7, "best" : 10}, {"gfg" : 2, "is" : 5, "best" : 9}, {"gfg" : 1, "is" : 2, "best" : 6}] Output : {'gfg': [1, 4], 'is': [2, 7],
11 min read
Python | Grouping list values into dictionary
Sometimes, while working with data, we can be encountered a situation in which we have a list of lists and we need to group its 2nd index with the common initial element in lists. Let's discuss ways in which this problem can be solved. Method 1: Using defaultdict() + loop + dict() The defaultdict ca
7 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
3 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Letâs discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops
10 min read
Python - Dictionary List Values Frequency
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the task of computing frequency of all the values in dictionary values lists. This is quite common problem and can have use cases in many domains. Let's discuss certain ways in which this task can be
6 min read