Reputation: 2755
I want to collect results for each date.
For each date increment pass fail results and add date in dict if not there. Should I go with dict in dict or defaultdict?
e.g. 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.
Upvotes: 3
Views: 673
Reputation: 164793
Simplest, as @Jean-FrançoisFabre points out, is to use a defaultdict
of Counter
objects.
The collections
documentation contains detailed information on these tools.
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})})
Upvotes: 3