我有一本字典如下:
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&# 39;并且' Dropping'分别。结果输出应为:
date Booming OutofService Peaking Constant Dropping
201505 1 2 1 2 1
我怎样才能做到这一点?
提前致谢!
答案 0 :(得分:2)
您可以通过提取相关数据,将其存储到列表然后将列表传递给collections.Counter()
来计算频率,http://en.wikipedia.org/wiki/Percent-encoding返回一个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