Skip to content
Advertisement

Aggregating dicts within a list based on key value

I’m struggling to wrap my head around this one. I’ve got a list with multiple dictionaries that I would like to aggregate based on two values. Example code:

JavaScript

I’m trying to aggregate dicts that have the same age and regex and adding the count key across all instances. Example output would be:

JavaScript

Would like to do this without pandas or addon modules, would prefer a solution from the std lib if at all possible.

Thanks!

Advertisement

Answer

Assuming you do not want to use any imports, you can first collect the data in a dictionary aggregated_data in which the key will be a tuple of (regex, age), and the value will be the count. Once you have formed this dictionary, you can form back the original structure you had:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement