Created
March 14, 2021 06:57
-
-
Save ktmud/b7eae18246e3e8f4463792e369f369fd to your computer and use it in GitHub Desktop.
Python Remove Duplicates by Key
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( | |
items: Iterable[InputType], key: Optional[Callable[[InputType], Any]] = None | |
) -> List[InputType]: | |
"""Remove duplicate items in an iterable.""" | |
if not key: | |
return list(dict.fromkeys(items).keys()) | |
seen = set() | |
result = [] | |
for item in items: | |
item_key = key(item) | |
if item_key not in seen: | |
seen.add(item_key) | |
result.append(item) | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment