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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read