Predicate Functions on Dictionary Properties

PythonPythonBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") subgraph Lab Skills python/comments -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} python/booleans -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} python/lists -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} python/tuples -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} python/dictionaries -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} python/function_definition -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} python/lambda_functions -.-> lab-13599{{"`Predicate Functions on Dictionary Properties`"}} end

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.

Other Python Tutorials you may like