Skip to content

Instantly share code, notes, and snippets.

@hsleonis
Created May 25, 2020 22:41
Show Gist options
  • Save hsleonis/4e0b769420be97f83716e91fa2ce6578 to your computer and use it in GitHub Desktop.
Save hsleonis/4e0b769420be97f83716e91fa2ce6578 to your computer and use it in GitHub Desktop.
Inverts a dictionary with non-unique hashable values.
def inverse_dict(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj
ages = {
  "Car": 5,
  "Bat": 5,
  "Ball": 8,
}
inverse_dict(ages) # { 5: ["Car", "Bat"], 8: ["Ball"] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment