简体   繁体   中英

Python: count specific occurrences in a dictionary

Say I have a dictionary like this:

d={
'0101001':(1,0.0), 
'0101002':(2,0.0),
'0101003':(3,0.5),
'0103001':(1,0.0),
'0103002':(2,0.9),
'0103003':(3,0.4),
'0105001':(1,0.0),
'0105002':(2,1.0),
'0105003':(3,0.0)}

Considering that the first four digits of each key consitute the identifier of a "slot" of elements (eg, '0101', '0103', '0105'), how can I count the number of occurrences of 0.0 for each slot?

The intended outcome is a dict like this:

result={
'0101': 2,
'0103': 1,
'0105': 2} 

Apologies for not being able to provide my attempt as I don't really know how to do this.

Use a Counter , add the first four digits of the key if the value is what you're looking for:

from collections import Counter

counts = Counter()

for key, value in d.items():
    if value[1] == 0.0:
        counts[key[:4]] += 1

print counts

You can use a defaultdict :

from _collections import defaultdict

res = defaultdict(int)
for k in d:
    if d[k][1] == 0.0:
        res[k[:4]] += 1

print(dict(res))

When you do the +=1 , if the key does not exist, it creates it with value 0 and then does the operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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