Created
June 15, 2021 13:08
-
-
Save pifabs/e42f1679ad8d270fdc47d3ffeac64632 to your computer and use it in GitHub Desktop.
Remove duplicate dicts in list having the same values for a given set of keys
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
def remove_duplicates_by_keys(arr, keys): | |
template = ":".join(["{{{}}}".format(key) for key in keys]) | |
return list({template.format(**el): el for el in arr}.values()) | |
data = [ | |
{ | |
"key1": "A", | |
"key2": "B" | |
}, | |
{ | |
"key1": "A", | |
"key2": "B" | |
}, | |
{ | |
"key1": "AA", | |
"key2": "BB" | |
} | |
] | |
result = remove_duplicates_by_keys(data, ["key1"]) | |
// [{'key1': 'A', 'key2': 'B'}, {'key1': 'AA', 'key2': 'BB'}] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment