2013-04-08 68 views
1

我有以下Python字典Python字典,计数元素值

resultDict: 
{'1234':{'alertStatus': 'open', 'reasonDescription': None}, 
'4321': {'alertStatus': 'closed', 'reasonDescription': 'Public'}, 
'6789': {'alertStatus': 'open', 'reasonDescription': 'None'}} 

我想算的开放数量和关闭警报(实际我有5个不同的状态,但在本例中,我减少它到2)

我写了下面的代码,但它看起来很不整洁。我想知道是否有更好的方式来做到这一点

result = {} 
result['length'] = len(resultDict) 
lenOpen = 0 
lenClosed = 0 

for notifications in resultDict.values(): 
    if notifications['alertStatus'] == 'open': 
     lenOpen = lenOpen + 1 
    if notifications['alertStatus'] == 'closed': 
     lenClosed = lenClosed + 1 

statusCount = [] 
if lenOpen > 0: 
    statusCount.append(str(lenOpen) + ' ' + 'open') 
if lenOpenUnderInvestigation > 0: 
    statusCount.append(str(lenClosed) + ' ' +'closed') 

result['statusCount'] = statusCount 

回答

2

您可以使用collections.Counter

In [2]: dic={'1234':{'alertStatus': 'open', 'reasonDescription': None}, 
    ...: '4321': {'alertStatus': 'closed', 'reasonDescription': 'Public'}, 
    ...: '6789': {'alertStatus': 'open', 'reasonDescription': 'None'}} 

In [3]: from collections import Counter 

In [4]: Counter(v['alertStatus'] for k,v in dic.items()) 

Out[4]: Counter({'open': 2, 'closed': 1}) 

帮助(计数器)

快译通子类,用于计算哈希的项目。有时候叫一个包或者多套。元素存储为字典键值,它们的计数值为 ,存储为字典值。

0

这样的事情呢?

alertStatuses = [x['alertStatus'] for x in resultDict.values()] 

然后,您可以使用Counter object来计算那里的元素。