Python: Filter the height and width of students which are stored in a dictionary using lambda
Python Lambda: Exercise-34 with Solution
Write a Python program to filter the height and width of students, which are stored in a dictionary using lambda.
Sample Solution:
Python Code :
# Define a function 'filter_data' that takes a dictionary 'students' as input
def filter_data(students):
# Use the 'filter' function with a lambda function to filter dictionary items based on height and weight conditions
# Only items with height > 6.0 and weight > 70 are kept in the resulting dictionary 'result'
result = dict(filter(lambda x: (x[1][0], x[1][1]) > (6.0, 70), students.items()))
# Return the filtered dictionary
return result
# Create a dictionary 'students' with student names as keys and tuples representing height and weight as values
students = {
'Cierra Vega': (6.2, 70),
'Alden Cantrell': (5.9, 65),
'Kierra Gentry': (6.0, 68),
'Pierre Cox': (5.8, 66)
}
# Print the original dictionary 'students'
print("Original Dictionary:")
print(students)
# Filter the dictionary 'students' based on height > 6ft and weight > 70kg using the 'filter_data' function
print("\nHeight > 6ft and Weight > 70kg:")
print(filter_data(students))
Sample Output:
Original Dictionary: {'Cierra Vega': (6.2, 70), 'Alden Cantrell': (5.9, 65), 'Kierra Gentry': (6.0, 68), 'Pierre Cox': (5.8, 66)} Height> 6ft and Weight> 70kg: {'Cierra Vega': (6.2, 70)}
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length using lambda.
Next: Write a Python program to check whether a specified list is sorted or not using lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-34.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics