Python字典,计算元素值

2024-10-01 07:49:45 发布

您现在位置: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

Tags: noneifresultopennotifications词典closedappend
2条回答

像这样的怎么样?你知道吗

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

然后可以使用Counter object从那里计算元素。你知道吗

您可以使用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 subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

相关问题 更多 >