Python – Assign pair elements from Tuple Lists
Last Updated :
04 Apr, 2023
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
test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )]
print ( "The original list : " + str (test_list))
res = dict ()
for key, val in test_list:
res.setdefault(val, [])
res.setdefault(key, []).append(val)
print ( "The resultant pairings : " + str (res))
|
Output
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
test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )]
print ( "The original list : " + str (test_list))
res = dict ()
for i in test_list:
res[i[ 0 ]] = [i[ 1 ]]
x = test_list[ - 1 ]
res[x[ 1 ]] = []
print ( "The resultant pairings : " + str (res))
|
Output
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
test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )]
print ( "The original list : " + str (test_list))
res = {x[ 0 ]: [y[ 1 ] for y in test_list if y[ 0 ] = = x[ 0 ]] for x in test_list}
|
Output
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))
|
Output
{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 )]
sorted_list = sorted (test_list, key = lambda x: x[ 0 ])
grouped_list = itertools.groupby(sorted_list, key = lambda x: x[ 0 ])
result = {key: [val[ 1 ] for val in value] for key, value in grouped_list}
print (result)
|
Output
{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
test_list = [( 5 , 3 ), ( 7 , 5 ), ( 2 , 7 ), ( 3 , 8 ), ( 8 , 4 )]
arr = np.array(test_list)
transpose_arr = np.transpose(arr)
unique_vals = np.unique(transpose_arr)
res = {}
for val in unique_vals:
indices = np.where(transpose_arr = = val)
extracted_vals = [arr[i] for i in indices[ 1 ]]
res[val] = extracted_vals
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
Similar Reads
Python | Binary Group Tuple list elements
Sometimes, while working with tuples, we can have problems of grouping them, be it based on gender or any particular binary category. This can have applications in many domains. Let's discuss certain ways in which this can be performed. Method #1 : Using generator + loop + zip() The brute force meth
4 min read
Get first element from a List of tuples - Python
The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of
2 min read
Python - Pair lists elements to Dictionary
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
6 min read
Python program to remove last element from Tuple
Given a tuple, the task is to write a Python program to delete the last element in the tuple in Python. Example: Input: ("geeks", "for", "geeks") Output:("geeks", "for") Explanation: Here we are deleting the last element of the tuple and finally modifying the original one. Note: Tuples are immutable
3 min read
Getting an Element from Tuple of Tuples in Python
Tuples in Python are versatile data structures that allow you to store and organize collections of elements. When dealing with tuples of tuples, accessing specific elements becomes essential for effective data manipulation. In this article, we'll explore some different methods to retrieve elements f
2 min read
Python - Cross Pairing in Tuple List
Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches. Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] Output : [(7, 3)] Explanation : 1 occurs as tuple element at pos. 1 in
5 min read
Python - Alternate list elements as key-value pairs
Given a list, convert it into dictionary by mapping alternate elements as key-value pairs. Input : test_list = [2, 3, 5, 6, 7, 8] Output : {3: 6, 6: 8, 2: 5, 5: 7} Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate] Input : test_list = [2, 3, 5, 6] Output : {3: 6,
2 min read
Python - Append Missing Elements from Other List
We are given two lists, and our task is to append elements from the second list to the first list, but only if they are not already present. This ensures that the first list contains all unique elements from both lists without duplicates. For example, if a = [1, 2, 3] and b = [2, 3, 4, 5], the resul
3 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task c
3 min read
Python | Find overlapping tuples from list
Sometimes, while working with tuple data, we can have a problem in which we may need to get the tuples which overlap a certain tuple. This kind of problem can occur in Mathematics domain while working with Geometry. Let's discuss certain ways in which this problem can be solved. Method #1 : Using lo
5 min read