英文:
how to count different keys with conditions in list of dictionaries
问题
我有一个字典列表,看起来像这样:它们在字典中有不同的键
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"}
]
我想要计算如果在字典中有“releaseDate”作为键并且日期在2023-01-01之后的情况下,计数id。
所以这个示例的最终结果应该是2
```python
2
任何帮助都会非常感激!
<details>
<summary>英文:</summary>
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!!**
</details>
# 答案1
**得分**: 3
只需将您的话翻译成Python代码即可:
```python
c = sum('releaseDate' in md and md['releaseDate'] >= '2023-01-01' for md in my_dicts)
尽管您甚至可以将其简化为:
c = sum(md.get('releaseDate', '0000-00-00') >= '2023-01-01' for md in my_dicts)
英文:
It's just a matter of translating your words into Python code:
c = sum('releaseDate' in md and md['releaseDate'] >= '2023-01-01' for md in my_dicts)
although you could even simplify it to:
c = sum(md.get('releaseDate', '0000-00-00') >= '2023-01-01' for md in my_dicts)
答案2
得分: 3
你可以在推导式中使用.get()
来检查是否存在并比较值:
sum(d.get("releaseDate", "") > "2023-01-01" for d in my_dicts) # 2
英文:
You can use .get() to check for presence and compare values in a comprehension:
sum(d.get("releaseDate","")>"2023-01-01" for d in my_dicts) # 2
答案3
得分: 1
你可以使用get()
函数,它提供了从字典中安全提取值的方式。如果字典中没有这个键(默认为None
),你可以定义想要获取的结果。对于你的情况,代码如下所示:
filtered_dicts = [
single_dict
for single_dict in my_dicts
if single_dict.get("releaseDate", "") >= "2023-01-01"
]
这将给你一个满足条件的字典列表。如果你只想计算它们的数量,你可以使用一行代码并加入len()
函数。
len(
[
single_dict
for single_dict in my_dicts
if single_dict.get("releaseDate", "") >= "2023-01-01"
]
)
英文:
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"
]
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论