Selective value selection in list of tuples in Python

PythonServer Side ProgrammingProgramming

When it is required to find the selective value in a list of tuples, the 'dict' method, the 'get' method and the list comprehension can be used.

The list comprehension is a shorthand to iterate through the list and perform operations on it. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

The 'dict' method creates a dictionary. It contains key value pairs, which are unordered, and indexed.

The 'get' method returns the value of a specific key when the key is present in a dictionary.

Below is a demonstration for the same −


Live Demo

my_list_1 = [('Jane', 11), ('Nick', 12), ('Will', 33), ('Paul', 14)]

my_list_2 = ['Nick', 'Paul']

print ("The list of tuple is : ")
print ("The second list is : ")
temp_val = dict(my_list_1)

my_result = [temp_val.get(i, 0) for i in my_list_2]

print ("The selective values of the keys are : ")


The list of tuple is :
[('Jane', 11), ('Nick', 12), ('Will', 33), ('Paul', 14)]
The second list is :
['Nick', 'Paul']
The selective values of the keys are :
[12, 14]


  • A list of tuple is defined, and is displayed on the console.
  • Another list is defined.
  • A dictionary is created from the list of tuple.
  • This is used to iterate over the other list.
  • This value is assigned to another variable.
  • This variable is displayed as output on the console.
Published on 13-Mar-2021 05:41:15