简体   繁体   English

Python:计算字典中的特定出现次数

[英]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? 考虑到每个键的前四位数字构成元素“槽”的标识符(例如,“ 0101”,“ 0103”,“ 0105”),我如何计算每个槽的出现次数0.0

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: 如果值是您要查找的值,请使用Counter ,添加密钥的前四位数字:

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 : 您可以使用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. 当您执行+=1 ,如果键不存在,它将创建一个值为0 ,然后执行该操作。

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

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