Skip to content

Instantly share code, notes, and snippets.

@sebastianschramm
Created August 18, 2022 15:24
Show Gist options
  • Save sebastianschramm/eb4a50f25fa183d841c91d6ee0662d7c to your computer and use it in GitHub Desktop.
Save sebastianschramm/eb4a50f25fa183d841c91d6ee0662d7c to your computer and use it in GitHub Desktop.
How to get a Counter of dictionaries from a list of dictionaries?
import operator
from itertools import groupby
list_of_city_dicts = [
{"city": "New York", "country": "US"},
{"city": "San José", "country": "CR"},
{"city": "New York", "country": "US"},
{"city": "San José", "country": "CO"},
{"city": "Puerto Viejo", "country": "CR"},
]
key_func = operator.itemgetter("city", "country")
grouped_dicts = groupby(sorted(list_of_city_dicts, key=key_func))
city_counter = {key_func(keys): len(list(group)) for keys, group in grouped_dicts}
"""
>>> city_counter
{('New York', 'US'): 2,
('Puerto Viejo', 'CR'): 1,
('San José', 'CO'): 1,
('San José', 'CR'): 1}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment