Skip to content

Instantly share code, notes, and snippets.

@ktmud
Created March 14, 2021 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktmud/b7eae18246e3e8f4463792e369f369fd to your computer and use it in GitHub Desktop.
Save ktmud/b7eae18246e3e8f4463792e369f369fd to your computer and use it in GitHub Desktop.
Python Remove Duplicates by Key
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