python - count repeated keys in a dict -
i have dict :
newdict ={'category': 'failure', 'week': '1209', 'stat': 'tdc_ok', 'severitydue': '2_critic', 'category': 'failure', 'week': '1210', 'stat': 'tdc_nok', 'severitydue': '2_critic'}
i want count stat
key week
, have tried :
>>> counterdict = defaultdict(counter) >>> in newdict : counterdict[int(newdict['week'])][newdict['stat']]+=1
but result :
[(1210, counter({'tdc_nok': 12}))]
i don't understand why 12
, why last week?
how can please?
you loop on dictionary keys, count same keys many times. there nothing dynamic loop body:
counterdict[int(newdict['week'])][newdict['stat']]+=1
if have 12 keys in dictionary, above line executed 12 times.
if expected see loop access multiple keys same name, misunderstood how dictionaries work. dictionaries map unique keys values. specifying key more once in literal dictionary declaration result in dictionary one copy of each key, one of values:
>>> {'foo': 'bar', 'foo': 'baz'} {'foo': 'baz'}
in cpython, compiler gives last value per key defined, why see 'week': '1210'
in example dictionary.
your sample input dictionary ends 4 unique keys:
>>> newdict ={'category': 'failure', 'week': '1209', 'stat': 'tdc_ok', 'severitydue': '2_critic', 'category': 'failure', 'week': '1210', 'stat': 'tdc_nok', 'severitydue': '2_critic'} >>> newdict {'category': 'failure', 'week': '1210', 'stat': 'tdc_nok', 'severitydue': '2_critic'} >>> len(newdict) 4
which makes me suspect ran loop 3 times come count of 12 (looping on dictionary gives 4 keys).
if have actual list of dictionaries, take each separate dictionary list , use basis of count:
for d in list_of_dictionaries: counterdict[int(d['week'])][d['stat']] += 1
where list_of_dictionaries
be:
[ {'category': 'failure', 'week': '1209', 'stat': 'tdc_ok', 'severitydue': '2_critic'}, {'category': 'failure', 'week': '1210', 'stat': 'tdc_nok', 'severitydue': '2_critic'}, ]
Comments
Post a Comment