user3349070
user3349070

Reputation: 27

How do you find the number of occurrence within a list of dictionaries

I'm trying to find how many times per case_id does email_response occurs in the example below:

json_obj = [{
    'case_id': 1000,
    'type': 'email',
    'customer_id': 42571,
    'date': '2015-01-20',
},
    {
    'case_id': 1000,
    'type': 'email_response',
    'customer_id': 42571,
    'date': '2015-01-21',
},
    {
    'case_id': 1021,
    'type': 'email',
    'customer_id': 88686,
    'date': '2015-01-24',
}]

So in this case, the answer would be 1 for case_id = 1000 and 0 for case_id = 1021.

Upvotes: 1

Views: 38

Answers (1)

thefourtheye
thefourtheye

Reputation: 239683

You can create another dictionary and keep on updating the count like this

>>> result = {}
>>> for obj in json_obj:
...     if obj['type'] == 'email_response':
...         result[obj['case_id']] = result.get(obj['case_id'], 0) + 1
...         
>>> result
{1000: 1, 1021: 0}

Since we pass 0 as the second parameter, the dict.get method will return 0 if it cannot find the key being retrieved, otherwise the actual value corresponding to the key. You can do the same like this

>>> result = {}
>>> for obj in json_obj:
...     result[obj['case_id']] = result.get(obj['case_id'], 0) + (obj['type'] == 'email_response')
...     
>>> result
{1000: 1, 1021: 0}

Since Python's booleans are subclasses of int, True will be 1 and False will be 0. So, the result of (obj['type'] == 'email_response') will be added with the current value of case_id in the result dictionary.

Upvotes: 1

Related Questions