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]} Explanation : Only one tuples, 5 paired with 3.
Method 1: Using setdefault() + loop
In this, we use brute way to solve this, iterate for each tuple, and set default values for each, key and value as empty list, appending the elements to the respective list if already present.
Step by step approach :
- Initialize a list of tuples test_list with some values.
- Print the original list test_list using the print() function and string concatenation.
- Initialize an empty dictionary res.
- Loop through each tuple in the list test_list using a for loop.
- For each tuple, extract its first and second elements into variables key and val respectively.
- Use the setdefault() method on dictionary res to add a new key-value pair if the key does not exist yet in the dictionary, and set the value of the key to an empty list.
- Use the setdefault() method again on dictionary res to add a new key-value pair if the key does not exist yet in the dictionary, and set the value of the key to a list containing the current val.
- If the key already exists in the dictionary, append the current val to the existing list of values for that key.
Repeat steps 6-8 for the key and val variables swapped, so that the same process is done for the second element of each tuple. - Print the resulting dictionary res using the print() function and string concatenation.
Python3
# Python3 code to demonstrate working of # Assign pair elements from Tuple Lists # Using setdefault + loop # initializing list test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )] # printing string print ( "The original list : " + str (test_list)) # initializing dictionary res = dict () for key, val in test_list: # adding to both, corresponding keys and values res.setdefault(val, []) res.setdefault(key, []).append(val) # printing results print ( "The resultant pairings : " + str (res)) |
The original list : [(5, 3), (7, 5), (2, 7), (3, 8), (8, 4)] The resultant pairings : {3: [8], 5: [3], 7: [5], 2: [7], 8: [4], 4: []}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using for loop
Python3
# Python3 code to demonstrate working of # Assign pair elements from Tuple Lists # Initializing list test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )] # Printing string print ( "The original list : " + str (test_list)) # initializing dictionary res = dict () for i in test_list: res[i[ 0 ]] = [i[ 1 ]] x = test_list[ - 1 ] res[x[ 1 ]] = [] # printing results print ( "The resultant pairings : " + str (res)) |
The original list : [(5, 3), (7, 5), (2, 7), (3, 8), (8, 4)] The resultant pairings : {5: [3], 7: [5], 2: [7], 3: [8], 8: [4], 4: []}
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), since a dictionary is created with n key-value pairs.
Method #3: Use dictionary comprehension as shown below
Use dictionary comprehension to iterate over the elements of the list test_list. For each element, use a nested list comprehension to iterate over all elements of the list and select the second element of tuples that have the same first element as the current element. Then assign the list of selected second elements to the first element of the current element in a dictionary.
Python3
# Initializing list test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )] # Printing string print ( "The original list : " + str (test_list)) # Using dictionary comprehension to assign pair elements from tuple lists res = {x[ 0 ]: [y[ 1 ] for y in test_list if y[ 0 ] = = x[ 0 ]] for x in test_list} # printing results |
The original list : [(5, 3), (7, 5), (2, 7), (3, 8), (8, 4)]
Time complexity: O(n^2) where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Method 4: Using the defaultdict() method
In this method, we create a defaultdict with a default value of an empty list. We then iterate through the tuples in the test_list and append the second element to the list associated with the first element in the defaultdict. Finally, we convert the defaultdict to a regular dictionary and print the result.
Python3
from collections import defaultdict test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )] res = defaultdict( list ) for x, y in test_list: res[x].append(y) print ( dict (res)) |
{5: [3], 7: [5], 2: [7], 3: [8], 8: [4]}
The time complexity of the code is O(N), where N is the length of the input list, because we iterate over each element in the list exactly once.
The space complexity of the code is O(N), because we create a dictionary with N keys and lists of variable length associated with each key.
Method 5: Using the itertools.groupby() function.
Step-by-step approach:
- Import itertools module.
- Sort the test_list by the first element of each tuple using the sorted() function.
- Group the sorted test_list by the first element of each tuple using itertools.groupby() function.
- Convert the grouped result into a dictionary where the keys are the first elements of each tuple and the values are the second elements of each tuple. Use dictionary comprehension to do this.
- Print the dictionary.
Below is the implementation of the above approach:
Python3
import itertools test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )] # sort the test_list by the first element of each tuple sorted_list = sorted (test_list, key = lambda x: x[ 0 ]) # group the sorted_list by the first element of each tuple grouped_list = itertools.groupby(sorted_list, key = lambda x: x[ 0 ]) # convert the grouped result into a dictionary result = {key: [val[ 1 ] for val in value] for key, value in grouped_list} # print the dictionary print (result) |
{2: [7], 3: [8], 5: [3], 7: [5], 8: [4]}
Time complexity: Sorting the list takes O(n log n) time. Grouping the list using itertools.groupby() takes O(n) time. Converting the grouped result into a dictionary using dictionary comprehension takes O(n) time. So, the overall time complexity of this method is O(n log n).
Auxiliary space: This method uses O(n) extra space to store the sorted list, grouped result, and the dictionary.
Method 6: Using numpy arrays and functions
Step-by-step approach:
- Import numpy library
- Convert the tuple list to a numpy array using the numpy.array() function
- Transpose the array using numpy.transpose() function to separate the pairs
- Use numpy.unique() function to extract the unique values from the transposed array
- Create an empty dictionary to store the results
- Use a for loop to iterate over the unique values extracted
- Using numpy.where() function to identify the indices of the unique value in the transposed array
- Use the identified indices to extract the corresponding values from the transposed array
- Append the extracted values as a list to the dictionary using the unique value as the key
- Print the resultant dictionary
Python3
import numpy as np # initializing list test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )] # converting list to numpy array arr = np.array(test_list) # transposing the array to separate the pairs transpose_arr = np.transpose(arr) # extracting unique values from the transposed array unique_vals = np.unique(transpose_arr) # initializing an empty dictionary to store the results res = {} # iterating over unique values for val in unique_vals: # identifying the indices of the unique value in the transposed array indices = np.where(transpose_arr = = val) # extracting the corresponding values from the transposed array extracted_vals = [arr[i] for i in indices[ 1 ]] # appending the extracted values as a list to the dictionary using the unique value as the key res[val] = extracted_vals # printing the resultant dictionary print ( "The resultant pairings : " + str (res)) |
OUTPUT:
The resultant pairings : {2: [array([2, 7])], 3: [array([3, 8]), array([5, 3])], 4: [array([8, 4])], 5: [array([5, 3]), array([7, 5])], 7: [array([7, 5]), array([2, 7])], 8: [array([8, 4]), array([3, 8])]}
Time complexity: O(nlogn) – Sorting the numpy array
Auxiliary space: O(n) – Space required to store the dictionary