我有一个以下的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
答案 0 :(得分: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})
帮助(计数器)强>:
用于计算可散列物品的Dict子类。有时称为包或 多集。元素存储为字典键,它们的计数是 存储为字典值。
答案 1 :(得分:0)
这样的事情怎么样?
alertStatuses = [x['alertStatus'] for x in resultDict.values()]
然后你可以使用Counter object来计算那里的元素。