Skip to content

Instantly share code, notes, and snippets.

@sebastianschramm
Created August 17, 2022 15:44
Show Gist options
  • Save sebastianschramm/23c00062dd3466d00685caaa64e74807 to your computer and use it in GitHub Desktop.
Save sebastianschramm/23c00062dd3466d00685caaa64e74807 to your computer and use it in GitHub Desktop.
How to get set of dictionaries from a list of duplicate dictionaries?
import operator
from itertools import groupby
list_of_city_dicts = [
{"city": "New York"},
{"city": "Hamburg"},
{"city": "New York"},
{"city": "Puerto Viejo"},
]
key_func = operator.itemgetter("city")
grouped_dicts = groupby(sorted(list_of_city_dicts, key=key_func))
unique_dicts = [keys for keys, _ in grouped_dicts]
"""
>>> unique_dicts
[{'city': 'Hamburg'}, {'city': 'New York'}, {'city': 'Puerto Viejo'}]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment