filter a dictionary using dict comprehension


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
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()

{'math': 100, 'biology': 53, 'chemistry': 62, 'art': 78, 'history': 20}
{'math': 100, 'chemistry': 62, 'art': 78}
{'biology': 53, 'history': 20}