+

Python | Selective selection of values ​​in a list of tuples

Method # 1: Using dict () + get () + comprehension list
We can accomplish this particular task by first converting the list into a dictionary, and then applying a list comprehension to get the value of specific keys using the get function.

# Python3 demo code
# Selective selection value in a list of tuples
# using dict () + get () + comprehension list

 
# initialize the list of tuples

test_list = [( `Nikhil` , 1 ), ( ` Akash` , 2 ), ( `Akshat ` , 3 ), ( `Manjeet` , 4 )]

 
# picklist initialization

select_list = [ `Nikhil` , `Akshat` ]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# print selection list

print ( "The selection list is:" + str (select_list))

 
# using dict () + get () + comprehension list
# Selective selection value in a list of tuples

temp = dict (test_list)

res = [temp.get (i, 0 ) for i in select_list]

 
# print result

print ( "The selective values ​​of keys:" + str (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]

Method # 2: Using next () + list comprehension
This particular the problem can be solved with the following function, which iterates using iterators and therefore a more efficient way to achieve a possible solution.

# Python3 demo code
# Selective selection value in list of tuples
# using next () + list comprehension

 
# initializing the list of tuples

test_list = [( `Nikhil` , 1 ), ( ` Akash` , 2 ), ( `Akshat` , 3 ), ( ` Manjeet` , 4 )]

 < / code> 
# select list initialization

select_list = [ `Nikhil` , `Akshat` ]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# print selection list

print ( "The selection list is:" + str (select_list))

  
# using next () + list comprehension
# Custom value selection in the list of tuples

res = [ next ((sub [ 1 ] for sub in test_list 

if sub [ 0 ] = = i), 0 ) for i in select_list]

 
# print result

print ( "The selective values ​​of keys:" + str (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]

Get Solution for free from DataCamp guru