Prim
Prim

Reputation: 1364

Python dictionary of dictionaries, counting element value

I have a following python dictionary

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)

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

Upvotes: 1

Views: 100

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

You can use 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. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

Upvotes: 2

Sajjan Singh
Sajjan Singh

Reputation: 2553

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.

Upvotes: 0

Related Questions