gpt4 book ai didi

python - 如何计算嵌套字典中的项目

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:07 25 4
gpt4 key购买 nike

我想收集每个日期的结果。

对于每个日期增量传递失败结果,如果不存在则在字典中添加日期。我应该使用 dict in dict 还是 defaultdict?

例如dates= {'2018-03-20': [{'pass': 2}, {'fail': 3}]}

我想添加新日期(如果不在日期中)并更新特定日期的“通过”/“失败”值。

最佳答案

正如@Jean-FrançoisFabre 指出的那样,最简单的方法是使用 Counter 对象的 defaultdict

集合 documentation包含有关这些工具的详细信息。

from collections import defaultdict, Counter

d = defaultdict(Counter)

d['2018-03-20']['pass'] += 1
d['2018-03-20']['fail'] += 1
d['2018-03-20']['pass'] += 1
d['2018-04-20']['pass'] += 1
d['2018-05-20']['pass'] += 1
d['2018-04-20']['fail'] += 1

结果:

defaultdict(collections.Counter,
{'2018-03-20': Counter({'fail': 1, 'pass': 2}),
'2018-04-20': Counter({'fail': 1, 'pass': 1}),
'2018-05-20': Counter({'pass': 1})})

关于python - 如何计算嵌套字典中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com