Predicate Functions on Dictionary Properties

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can create functions that take in a dictionary and apply a predicate function to a specified property of the dictionary. This can be useful in scenarios where we need to check if a certain condition is met for a specific property of a dictionary.

Check Property

Create a function called check_prop that takes in two parameters: fn and prop. The fn parameter is a predicate function that will be applied to the specified property of a dictionary. The prop parameter is a string that represents the name of the property that the predicate function will be applied to.

The check_prop function should return a lambda function that takes in a dictionary and applies the predicate function, fn, to the specified property.

def check_prop(fn, prop):
  return lambda obj: fn(obj[prop])
check_age = check_prop(lambda x: x >= 18, 'age')
user = {'name': 'Mark', 'age': 18}
check_age(user) ## True

Summary

In this challenge, you learned how to create a function that applies a predicate function to a specified property of a dictionary. This can be useful in scenarios where we need to check if a certain condition is met for a specific property of a dictionary.