How to extract group count from dictionary?

Viewed 159

I need to get the count of groups which is same 'id' and 'name'

Input:

myd = {
  "Items": [
    {
      "id": 1,
      "name": "ABC",
      "value": 666
    },
    {
      "id": 1,
      "name": "ABC",
      "value": 89
    },
    {
      "id": 2,
      "name": "DEF",
      "value": 111
    },
    {
      "id": 3,
      "name": "GHI",
      "value": 111
    }
  ]
}

Expected output:

The count of {'id':1, 'name': 'ABC' } is 2
The count of {'id':2, 'name': 'DEF' } is 1
The count of {'id':3, 'name': 'GHI' } is 1

for total length we can get by len(myd) for single key its len(myd['id'])

How to get the count for the combination of id and name

2 Answers

You can use collections.OrderedDict and set both 'id' and 'name' as tuple keys. In this way, the OrderedDict automatically groups the dictionaries with same 'id' and 'name' values in order:

myd = {'Items': [
{'id':1, 'name': 'ABC', 'value': 666},
{'id':1, 'name': 'ABC', 'value': 89},
{'id':2, 'name': 'DEF', 'value': 111 },
{'id':3, 'name': 'GHI', 'value': 111 }]
}

from collections import OrderedDict

od = OrderedDict()
for d in myd['Items']:
    od.setdefault((d['id'], d['name']), set()).add(d['value'])

for ks, v in od.items():
    print("The count of {{'id': {}, 'name': {}}} is {}".format(ks[0], ks[1], len(v)))

Output:

The count of {'id': 1, 'name': ABC} is 2
The count of {'id': 2, 'name': DEF} is 1
The count of {'id': 3, 'name': GHI} is 1

This is a good candidate for groupby and itemgetter usage:

from itertools import groupby
from operator import itemgetter

myd = {'Items': [
    {'id': 1, 'name': 'ABC', 'value': 666},
    {'id': 1, 'name': 'ABC', 'value': 89},
    {'id': 2, 'name': 'DEF', 'value': 111},
    {'id': 3, 'name': 'GHI', 'value': 111}]
}

grouper = itemgetter('id', 'name')

for i, v in groupby(sorted(myd['Items'], key=grouper), key=grouper):
    print(f"the count for {dict(id=i[0], name=i[1])} is {len(list(v))}")
Related