[英]Python dictionary of dictionaries, counting element value
I have a following python dictionary 我有以下python字典
resultDict:
{'1234':{'alertStatus': 'open', 'reasonDescription': None},
'4321': {'alertStatus': 'closed', 'reasonDescription': 'Public'},
'6789': {'alertStatus': 'open', 'reasonDescription': 'None'}}
I want to count number of open and closed alerts (in real i have 5 different status, but for this example i have reduced it to 2) 我想计算打开和关闭警报的数量(实际上我有5种不同的状态,但在本示例中,我将其减少为2种)
I have written the following code , but it looks pretty untidy. 我已经编写了以下代码,但是看起来很乱。 I was wondering if there is a better way to do it
我想知道是否有更好的方法
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
You can use collections.Counter
: 您可以使用
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})
help(Counter) : 帮助(计数器) :
Dict subclass for counting hashable items.
Dict子类,用于计算可哈希项。 Sometimes called a bag or multiset.
有时称为书包或多件套。 Elements are stored as dictionary keys and their counts are stored as dictionary values.
元素存储为字典键,其计数存储为字典值。
How about something like this? 这样的事情怎么样?
alertStatuses = [x['alertStatus'] for x in resultDict.values()]
Then you can count the elements from there with the Counter object . 然后,您可以使用Counter对象从此处计算元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.