Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to count different keys with conditions in list of dictionaries

I have a list of dicts looks like this: they have different keys in the dicts

my_dicts = [
    {"id": "1","fixVersion": "1.2.3","releaseDate": "2017-01-21"},
    {"id": "2","fixVersion": "2.0", "releaseDate": "2023-01-21"},
    {"id": "3","fixVersion": "2.1", "releaseDate": "2023-07-01"},
    {"id": "84","changeRequests":"123"}
]

I want to count the id if there is "releaseDate" as the key in the dictionaries and also the date is after 2023-01-01.

so the final result should be 2 for this example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2

any help is really appreciated!!

>Solution :

You can use get() function, that provides safe extraction from the dict. You can define what do you want to get as a result, if there’s no such key in a dict (it’s None by default).
For your case it would look like this:

filtered_dicts = [
    single_dict
    for single_dict in my_dicts
    if single_dict.get("releaseDate", "") >= "2023-01-01"
]

This will give you the list of dicts that satisfy your condition. If you want to count them only, you can do a one-liner with throwing in len() function.

len(
    [
        single_dict
        for single_dict in my_dicts
        if single_dict.get("releaseDate", "") >= "2023-01-01"
    ]
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading