Python | Selective value selection in list of tuples
Last Updated :
02 May, 2023
Sometimes, while using list of tuples, we come across a problem in which we have a certain list of keys and we just need the value of those keys from list of tuples. This has a utility in rating or summation of specific entities. Let's discuss certain ways in which this can be done.
Method #1 : Using dict() + get() + list comprehension
We can perform this particular task by first, converting the list into the dictionary and then employing list comprehension to get the value of specific keys using get function.
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using dict() + get() + list comprehension
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using dict() + get() + list comprehension
# Selective Value selection in list of tuples
temp = dict(test_list)
res = [temp.get(i, 0) for i in select_list]
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.
Method #2: Using next() + list comprehension
This particular problem can be solved using the next function which performs the iteration using the iterators and hence more efficient way to achieve a possible solution.
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using next() + list comprehension
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using next() + list comprehension
# Selective Value selection in list of tuples
res = [next((sub[1] for sub in test_list
if sub[0] == i), 0) for i in select_list]
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using for loop
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
res = []
for i in select_list:
for j in range(0, len(test_list)):
if(test_list[j][0] == i):
res.append(test_list[j][1])
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time complexity: O(n * m), where n is the length of the select_list and m is the length of the test_list.
Auxiliary space: O(k), where k is the length of the res list.
Method #4 : Using list comprehension without dict()
Here is an example of how you can use list comprehension to selectively select values from a list of tuples:
Python3
# Initialize the list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# Initialize the selection list
select_list = ['Nikhil', 'Akshat']
# Selectively select the values using list comprehension
res = [tuple[1] for tuple in test_list if tuple[0] in select_list]
print(res) # Output: [1, 3]
# This code is contributed by Edula Vinay Kumar Reddy
Time complexity: O(n), where n is the number of tuples in the test_list.
Auxiliary space: O(m), where m is the number of selected names in the select_list.
Method #5: Using filter() + map() function
- Initialize the list of tuples
- Initialize the selection list
- Define a lambda function that takes in a tuple and returns True if the first element of the tuple is in the selection list, otherwise False
- Use the filter() function to create a new list of tuples that match the selection criteria
- Use the map() function to extract the second element of each tuple in the filtered list
- Convert the map object to a list
- Print the resulting list of values
Python3
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using filter() + map() function
# Selective Value selection in list of tuples
res = list(map(lambda x: x[1], filter(lambda x: x[0] in select_list, test_list)))
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using a dictionary comprehension
Create a dictionary comprehension that filters the original list of tuples by checking if the first element of each tuple is in the selection list, and returns a dictionary with keys equal to the first element of the tuples and values equal to the second element of the tuples.
Use a list comprehension to create a list of values from the resulting dictionary.
Python3
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using a dictionary comprehension
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# using a dictionary comprehension
# Selective Value selection in list of tuples
res_dict = {k: v for k, v in test_list if k in select_list}
res = [res_dict[k] for k in select_list]
# printing result
print("The selective values of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time complexity: O(n)
Auxiliary space: O(n)
Approach using Numpy:
Note: Install numpy module using command "pip install numpy"
Algorithm:
Convert the list of tuples into a NumPy array.
Extract the first and second columns of the array separately as two 1D arrays.
Use np.where() function to get the indices where the first column matches the values in select_list.
Use the above indices to get the corresponding values from the second array.
Return the resulting array.
Python3
import numpy as np
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# converting the list of tuples to a NumPy array
arr = np.array(test_list)
# extracting the first and second columns separately
col1 = arr[:, 0]
col2 = arr[:, 1]
# getting the indices where the first column matches the values in select_list
indices = np.where(np.isin(col1, select_list))
# using the indices to get the corresponding values from the second column
res = list(map(int,col2[indices]))
# printing the resulting array
print("The selective values of keys : " + str(list(res)))
Output:
The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values of keys : [1, 3]
Time Complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.
Note: The time complexity of the NumPy solution is the same as the dict() solution, but it may have better performance due to NumPy's efficient array operations.
Similar Reads
Sort a List of Tuples by Second Item - Python The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
2 min read
How To Slice A List Of Tuples In Python? In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read
Unzip List of Tuples in Python The task of unzipping a list of tuples in Python involves separating the elements of each tuple into individual lists, based on their positions. For example, given a list of tuples like [('a', 1), ('b', 4)], the goal is to generate two separate lists: ['a', 'b'] for the first elements and [1, 4] for
2 min read
Python | Get first index values in tuple of strings Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the fi
5 min read
Flatten tuple of List to tuple - Python The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
3 min read
Python | Selective Records Value Summation Sometimes, while using a list of tuples, we come across a problem in which we have e certain list of keys and we just need the summation of values of those keys from the list of tuples. This has a utility in rating or summation of specific entities. Letâs discuss certain ways in which this can be do
11 min read
Python - Restrict Tuples by frequency of first element's value Given a Tuple list, the task is to write a Python program to restrict the frequency of the 1st element of tuple values to at most K. Examples: Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 2 Output : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4),
3 min read
Python | Selective key values in dictionary Sometimes while working with Python dictionaries, we might have a problem in which we require to just get the selective key values from the dictionary. This problem can occur in web development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehensio
7 min read
Python - Remove Tuples of Length K Given list of tuples, remove all the tuples with length K. Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2 Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] Explanation : (4, 5) of len = 2 is removed. Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K =
6 min read