Posts

Showing posts with the label groupby

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

How to get the set of dictionaries from a list of dictionaries with duplicates?



To find the set of dictionaries from a list of dictionaries with duplicates we can use itertools.groupby. The important part is that the list of dictionaries is sorted by the keys of the dicts before applying groupby. In our example this is key='city'. To obtain the list of unique dicts we use only the key part of the tuple returned by the groupby iterator.


Github gist with code

dependencies: python3.9