Selective value selection in list of tuples in Python


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 −

Example

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(my_list_1)
print ("The second list is : ")
print(my_list_2)
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 : ")
print(my_result)

Output

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]

Explanation

  • 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.

Updated on: 13-Mar-2021

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements