From e8961d531db9b7b784fffcef2a94e3ecd8662f74 Mon Sep 17 00:00:00 2001 From: Gabor Szabo Date: Wed, 1 Jan 2025 11:13:53 +0200 Subject: [PATCH] add --- .../examples/functional/filter_dictionary.out | 3 +++ .../examples/functional/filter_dictionary.py | 18 ++++++++++++++++++ python/functional.md | 9 +++++++++ 3 files changed, 30 insertions(+) create mode 100644 python/examples/functional/filter_dictionary.out create mode 100644 python/examples/functional/filter_dictionary.py diff --git a/python/examples/functional/filter_dictionary.out b/python/examples/functional/filter_dictionary.out new file mode 100644 index 000000000..b9dc58ad7 --- /dev/null +++ b/python/examples/functional/filter_dictionary.out @@ -0,0 +1,3 @@ +{'math': 100, 'biology': 53, 'chemistry': 62, 'art': 78, 'history': 20} +{'math': 100, 'chemistry': 62, 'art': 78} +{'biology': 53, 'history': 20} diff --git a/python/examples/functional/filter_dictionary.py b/python/examples/functional/filter_dictionary.py new file mode 100644 index 000000000..74b2a1c1c --- /dev/null +++ b/python/examples/functional/filter_dictionary.py @@ -0,0 +1,18 @@ +def main(): + grades = { + "math": 100, + "biology": 53, + "chemistry": 62, + "art": 78, + "history": 20, + } + print(grades) + + good_grades = {key: value for (key, value) in grades.items() if value >= 60} + print(good_grades) + + bad_grades = {key: grades[key] for key in grades if grades[key] < 60} + print(bad_grades) + + +main() diff --git a/python/functional.md b/python/functional.md index ac6c11c39..9919dc290 100644 --- a/python/functional.md +++ b/python/functional.md @@ -444,6 +444,15 @@ This can have only one iterable! ![](examples/functional/filter_map_one.py) ![](examples/functional/filter_map_one.out) +## filter a dictionary using dict comprehension +{id: filter-a-dictionary} + +We have a dictionary, we would like to create another dictionary based on this one that contains only key-value pairs that meet a certain condition. + +![](examples/functional/filter_dictionary.py) +![](examples/functional/filter_dictionary.out) + + ## Get indices of values {id: get-indexes-of-values}