1

我有以下 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
4

2 回答 2

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})

帮助(计数器)

用于计算可散列项的字典子类。有时称为包或多组。元素存储为字典键,它们的计数存储为字典值。

于 2013-04-08T18:10:47.597 回答
0

这样的事情怎么样?

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

然后,您可以使用Counter 对象从那里计算元素。

于 2013-04-08T18:11:13.973 回答