Posts

Showing posts with the label dicts

How to obtain a Counter from a list of dictionaries similar to collections.Counter for simple types?



If we have a list of integers we can use collections.Counter to obtain a counter for those integers. If we have a list of dictionaries simply applying collections.Counter will not work. One way to get a counter of dicts from a list of dictionaries is to use itertools.groupby. 

Note in the example that the city San José appears twice but in different countries. Our counter correctly keeps them separate since we are using both keys, city and country, for sorting and groupby. If we would use only city as key (like in yesterday's post), the counter would show 2 for San José.


Github gist with code

dependencies: python3.9