1

I have a class for example:

class Row(object):
    def __init__(self, res_json):
        test = res_json['test']
        value = res_json['value']
        year = res_json['date'][0:4]

If I have a list of row objects and want to group them by year what's the best way to do this?

staten12
  • 735
  • 3
  • 9
  • 20
  • Possible duplicate of [Parsing a json and grouping contents](https://stackoverflow.com/questions/32497253/parsing-a-json-and-grouping-contents) – Stevy Apr 01 '19 at 14:21
  • 1
    Yes, I'm actually trying to avoid pandas due to schema issues with our system – staten12 Apr 01 '19 at 14:21

1 Answers1

2

Use itertools.groupby:

from itertools import groupby
from operator import attrgetter

rows = []  # list of row objects

for year, group in groupby(rows, key=attrgetter('year')):
    # do stuff with the year and the group here
gmds
  • 19,325
  • 4
  • 32
  • 58