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
# 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))
OutputThe 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))
OutputThe 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
OutputThe 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)]
# 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)
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
# 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
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 me
4 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 - Assign K to Non Max-Min elements in Tuple
Sometimes, while working with Python data, we can have a problem in which we need to assign particular value as per certain condition. One of condition can be non-max, min element. This kind of task can occur in many application of day-day programming and competitive programming. Lets discuss certai
7 min read
Python - Add list elements to tuples list
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be don
6 min read
Python | Filter tuples according to list element presence
Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have applications in many domains working with data. Let's discuss certain ways in which this task can be performed.
8 min read
Python | Elementwise AND in tuples
Sometimes, while working with records, we can have a problem in which we may need to perform mathematical bitwise AND operation across tuples. This problem can occur in day-day programming. Letâs discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expression
5 min read
Python | Find Dissimilar Elements in Tuples
Sometimes, while working with tuples, we can have a problem in which we need dissimilar features of two records. This type of application can come in Data Science domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using set() + "^" operator This task can be performed
8 min read
Access front and rear element of Python tuple
Sometimes, while working with records, we can have a problem in which we need to access the initial and last data of a particular record. This kind of problem can have application in many domains. Let's discuss some ways in which this problem can be solved. Method #1: Using Access Brackets We can pe
6 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