Files
30-seconds-of-code/snippets/invert_dictionary.md
Isabelle Viktoria Maciohsek cbc78ee450 Bake dates into snippets
2021-06-13 19:38:10 +03:00

547 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
invert_dictionary dictionary,intermediate 2020-04-07T21:13:32+03:00 2020-11-02T19:28:05+02:00

Inverts a dictionary with unique hashable values.

  • Use dictionary.items() in combination with a list comprehension to create a new dictionary with the values and keys inverted.
def invert_dictionary(obj):
  return { value: key for key, value in obj.items() }
ages = {
  'Peter': 10,
  'Isabel': 11,
  'Anna': 9,
}
invert_dictionary(ages) # { 10: 'Peter', 11: 'Isabel', 9: 'Anna' }