Python - 计算值与特定查找字符串匹配的字典键的数量

Python - Count the number of dictionary keys with values that match a certain lookup string

我有一个字典如下:

Key       Value
5zd {'status': 'Outofservice', 'date': '201505'}
8km {'status': 'Peaking', 'date': '201505'}
erg {'status': 'Outofservice', 'date': '201505'}
xrg {'status': 'Booming', 'date': '201505', 'rate': 18.691588785046733, 'mean': 4}
86e {'status': 'Constant', 'date': '201505', 'rate': -9.6810933940774486, 'mean': -17}
4ld {'status': 'Constant', 'date': '201505', 'rate': -4.7619047619047619, 'mean': -1}
zzz {'status': 'Dropping', 'date': '201505', 'rate': -67.34693877551021, 'mean': -11}

我想分别统计一下值中包含'Booming'、'Outofservice'、'Peaking'、'Constant'和'Dropping'的键的个数。结果输出应为:

date    Booming    OutofService    Peaking    Constant    Dropping
201505  1          2               1          2           1

我怎样才能做到这一点?

提前致谢!

您可以通过提取相关数据,将其存储到列表然后将列表传递给collections.Counter()来计算频率,其中returns一个Counter对象表示频率每个元素都出现在给定列表中。

import collections

d = {'5zd': {'status': 'Outofservice', 'date': '201505'},
     '8km': {'status': 'Peaking', 'date': '201505'},
     'erg': {'status': 'Outofservice', 'date': '201505'},
     'xrg': {'status': 'Booming', 'date': '201505', 'rate': 18.691588785046733, 'mean': 4},
     '86e': {'status': 'Constant', 'date': '201505', 'rate': -9.6810933940774486, 'mean': -17},
     '4ld': {'status': 'Constant', 'date': '201505', 'rate': -4.7619047619047619, 'mean': -1},
     'zzz': {'status': 'Dropping', 'date': '201505', 'rate': -67.34693877551021, 'mean': -11}}

lst = [value["status"] for value in d.values()]

print collections.Counter(lst)
>>> Counter({'Outofservice': 2, 'Constant': 2, 'Peaking': 1, 'Booming': 1, 'Dropping': 1})

counter_obj = collections.Counter(lst)
for i in counter_obj:
    print i, counter_obj[i]
>>> Peaking 1
    Outofservice 2
    Booming 1
    Dropping 1
    Constant 2