简体   繁体   English

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

[英]How to count items in a nested dictionary

I want to collect results for each date. 我想收集每个日期的结果。

For each date increment pass fail results and add date in dict if not there. 对于每个日期增量传递失败结果并在dict中添加日期(如果不存在)。 Should I go with dict in dict or defaultdict? 我应该在dict或defaultdict中使用dict吗?

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

And I want to add new date if not in dates and updates 'pass'/ 'fail' value for specific date. 我想在日期中添加新日期,并在特定日期更新“通过”/“失败”值。

Simplest, as @Jean-FrançoisFabre points out, is to use a defaultdict of Counter objects. 正如@ Jean-FrançoisFabre指出的那样,最简单的方法是使用Counter对象的defaultdict

The collections documentation contains detailed information on these tools. collections 文档包含有关这些工具的详细信息。

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

Result: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM