Skip to content

Instantly share code, notes, and snippets.

@FMeinicke
Last active June 27, 2024 10:13
Show Gist options
  • Select an option

  • Save FMeinicke/41e68e1f27f5b7c84ee80817b12ab6b5 to your computer and use it in GitHub Desktop.

Select an option

Save FMeinicke/41e68e1f27f5b7c84ee80817b12ab6b5 to your computer and use it in GitHub Desktop.
A simple helper function to invert the keys and values of a Python `dict`
from __future__ import annotations
from typing import Dict, TypeVar, Callable
_K = TypeVar("_K")
_V = TypeVar("_V")
_KV = TypeVar("_KV")
def invert_dict(d: Dict[_K, _V], *, value_to_key: Callable[[_V], _KV] = lambda v: v) -> Dict[_V, _KV]:
"""
Inverts the keys and values of a dictionary.
Parameters
----------
d : dict
The dictionary to be inverted
Keyword Parameters
------------------
value_to_key : Callable, optional
A function to convert the values of the original dictionary before they are used as keys in the inverted
dictionary. This can be useful to ensure that the new keys are hashable.
By default, this function is the identity function, i.e., the values are used as keys without modification.
Returns
-------
dict
The inverted dictionary
"""
return dict([(value_to_key(v), k) for k, v in d.items()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment