Python – Pair lists elements to Dictionary
Last Updated :
01 Jun, 2023
Sometimes, while working with records we can have problems in which we can have pair of lists, we need to pair similar elements to a single key-value dictionary. This is a very peculiar problem but can have applications in data domains. Let us discuss certain ways in which this task can be performed.
Method #1 : Using loop + extend() + enumerate()
The combination of the above functionalities can be employed to solve this question. In this, we iterate for the lists and append like elements to a similar keys using extend().
Python3
test_list1 = [ 1 , 2 , 3 , 1 , 1 , 2 , 3 ]
test_list2 = [[ 4 , 5 ], [ 6 , 7 ], [ 2 , 3 ], [ 10 , 12 ],
[ 56 , 43 ], [ 98 , 100 ], [ 0 , 13 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = dict ()
for idx, val in enumerate (test_list1):
if val in res:
res[val].extend( list (test_list2[idx]))
else :
res[val] = list (test_list2[idx])
print ( "The Like elements compiled Dictionary is : " + str (res))
|
Output
The original list 1 is : [1, 2, 3, 1, 1, 2, 3]
The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]
The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]}
Time Complexity: O(n*n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
Method #2: Using defaultdict() + zip()
The combination of the above tasks can also be used to solve this problem. In this, we pair elements using zip() and initialize the dictionary values as a list to avoid testing for the existence of the first value.
Python3
from collections import defaultdict
test_list1 = [ 1 , 2 , 3 , 1 , 1 , 2 , 3 ]
test_list2 = [[ 4 , 5 ], [ 6 , 7 ], [ 2 , 3 ], [ 10 , 12 ],
[ 56 , 43 ], [ 98 , 100 ], [ 0 , 13 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = defaultdict( list )
for ele1, ele2 in zip (test_list1, test_list2):
res[ele1].extend(ele2)
print ( "The Like elements compiled Dictionary is : " + str ( dict (res)))
|
Output
The original list 1 is : [1, 2, 3, 1, 1, 2, 3]
The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]
The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]}
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the using defaultdict() + zip() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #3: Using a dictionary comprehension with list comprehension
Algorithm:
- Zip the two lists together to form a list of tuples.
- Use dictionary comprehension to create a new dictionary, where each key is a unique element from test_list1, and the value is a list of all corresponding elements from test_list2.
- Print the resulting dictionary.
Example:
Python3
test_list1 = [ 1 , 2 , 3 , 1 , 1 , 2 , 3 ]
test_list2 = [[ 4 , 5 ], [ 6 , 7 ], [ 2 , 3 ], [ 10 , 12 ],
[ 56 , 43 ], [ 98 , 100 ], [ 0 , 13 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = {key: [val for idx, val in enumerate (
test_list2) if test_list1[idx] = = key] for key in set (test_list1)}
print ( "The Like elements compiled Dictionary is : " + str (res))
|
Output
The original list 1 is : [1, 2, 3, 1, 1, 2, 3]
The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]
The Like elements compiled Dictionary is : {1: [[4, 5], [10, 12], [56, 43]], 2: [[6, 7], [98, 100]], 3: [[2, 3], [0, 13]]}
Time complexity: O(n^2) where n is the length of the input lists since we are using a nested loop to iterate over both lists.
Auxiliary space: O(n) since we are using a dictionary to store the result, which may contain up to n keys.
Method #4: Using itertools.groupby
In this method, we can use the itertools.groupby function to group the elements of the first list and then create a dictionary using a dictionary comprehension.
Python3
from itertools import groupby
test_list1 = [ 1 , 2 , 3 , 1 , 1 , 2 , 3 ]
test_list2 = [[ 4 , 5 ], [ 6 , 7 ], [ 2 , 3 ], [ 10 , 12 ], [ 56 , 43 ], [ 98 , 100 ], [ 0 , 13 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = {k: [sub for _, sub in g] for k, g in groupby( sorted ( zip (test_list1, test_list2)), key = lambda x: x[ 0 ])}
print ( "The Like elements compiled Dictionary is : " + str (res))
|
Output
The original list 1 is : [1, 2, 3, 1, 1, 2, 3]
The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]
The Like elements compiled Dictionary is : {1: [[4, 5], [10, 12], [56, 43]], 2: [[6, 7], [98, 100]], 3: [[0, 13], [2, 3]]}
Time complexity: O(n log n), because we use sorted function
Space complexity: O(n), since we are using a dictionary to store the result, which may contain up to n keys.
Similar Reads
Python - Check List elements from Dictionary List
Sometimes, while working with data, we can have a problem in which we need to check for list element presence as a particular key in list of records. This kind of problem can occur in domains in which data are involved like web development and Machine Learning. Lets discuss certain ways in which thi
4 min read
Python - Extract dictionary items with List elements
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let's discuss certain ways i
8 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its
4 min read
Python | Sort dictionary keys to list
Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python - Assign pair elements from Tuple Lists
Given a tuple list, assign each element, its pair elements from other similar pairs. Input : test_list = [(5, 3), (7, 5), (8, 4)] Output : {5: [3], 7: [5], 8: [4], 4: []} Explanation : 1st elements are paired with respective 2nd elements from all tuples. Input : test_list = [(5, 3)] Output : {5: [3]
7 min read
Python - Extract Equal Pair Dictionary
While working with a Python dictionary, we are supposed to create a new dictionary of the existing dictionary having tuple as key. We desire to create a singleton key dictionary with keys only where both elements of pair are equal. This can have applications in many domains. Let's discuss certain wa
5 min read
Get Random Dictionary Pair - Python
We are given a dictionary and our task is to retrieve a random key-value pair from it. For example, given the dictionary: d = {'aryan': 10, 'harsh': 20, 'kunal': 30} then a possible output could be any one of these: ('aryan', 10), ('harsh', 20), or ('kunal', 30). Using random.choice() In this method
2 min read
Python - Assign list items to Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop The combination o
10 min read
Convert List of Lists to Dictionary - Python
We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Python - Common list elements and dictionary values
Given list and dictionary, extract common elements of List and Dictionary Values. Input : test_list = ["Gfg", "is", "Best", "For"], subs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", } Output : ['Gfg'] Explanation : "Gfg" is common in both list and dictionary value. Input : test_list = ["Gfg", "is",
3 min read