Home > other >  check and count occurrence of particular key in list of dictionaries in python
check and count occurrence of particular key in list of dictionaries in python

Time:02-11

Question: Below is response body from GET call of REST API. I need to check occurrence of status and gender in response body and count how many Male active, Male inactive, Female active and Female Inactive are present.

Given Input: [{"id":3627,"name":"Arnesh Patil","email":"[email protected]","gender":"male","status":"active"},{"id":3626,"name":"Digambara Ahuja","email":"[email protected]","gender":"male","status":"inactive"},{"id":3625,"name":"Smriti Sharma Esq.","email":"[email protected]","gender":"female","status":"inactive"},{"id":3624,"name":"Vedanga Ganaka PhD","email":"[email protected]","gender":"male","status":"active"}]

After that we need to store output in below nested dictionary format:

Expected Ouptut

{ 'active': { 'male': 2, 'female': 0 }, 'inactive': { 'male': 1, 'female': 1 } }

how to parse List of dictionary and get output as shown above?

CodePudding user response:

Get a list of the genders of the people to which each statuses applies, and then count up the frequency of each gender for each status.

The first part can be done using list comprehensions. The Counter object in the built-in collections library is a convenient way to count frequencies for the second part.

Take a look at the following:

from collections import Counter

response = [
    {"id":3627,"name":"Arnesh Patil","email":"[email protected]","gender":"male","status":"active"},
    {"id":3626,"name":"Digambara Ahuja","email":"[email protected]","gender":"male","status":"inactive"},
    {"id":3625,"name":"Smriti Sharma Esq.","email":"[email protected]","gender":"female","status":"inactive"},
    {"id":3624,"name":"Vedanga Ganaka PhD","email":"[email protected]","gender":"male","status":"active"}
]

statuses = ['active', 'inactive']
output_dict = {}

for status in statuses:
    output_dict[status] = [person['gender'] for person in response
                           if (person['status']) == status]
output_dict = {status: dict(Counter(genders)) 
               for status, genders in output_dict.items()}

print(output_dict)

Outputs:

{'active': {'male': 2}, 'inactive': {'male': 1, 'female': 1}}

The 'male'/'female' keys are not included when there are 0 instances for a status, so if you need those keys to exist later you may need to adjust the code slightly.

CodePudding user response:

You can do it with standard dicts:

result = {"active":{}, "inactive" ={}}
for i in data:
    result.get(i.get("status"))[i.get("gender")] = result.get(i.get("status")).get(i.get("gender"),0) 1
  • Related