Created
August 17, 2022 15:44
-
-
Save sebastianschramm/23c00062dd3466d00685caaa64e74807 to your computer and use it in GitHub Desktop.
How to get set of dictionaries from a list of duplicate dictionaries?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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