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
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"
]
)