From d3a354f697b0467dd1cf172820faa6761cc6bf1b Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Tue, 7 Apr 2020 21:13:32 +0300 Subject: [PATCH] Add invert_dictionary --- snippets/invert_dictionary.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/invert_dictionary.md diff --git a/snippets/invert_dictionary.md b/snippets/invert_dictionary.md new file mode 100644 index 000000000..b30ef9572 --- /dev/null +++ b/snippets/invert_dictionary.md @@ -0,0 +1,22 @@ +--- +title: invert_dictionary +tags: dictionary,intermediate +--- + +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. + +```py +def invert_dictionary(obj): + return { value: key for key, value in obj.items() } +``` + +```py +ages = { + "Peter": 10, + "Isabel": 11, + "Anna": 9, +} +invert_dictionary(ages) # { 10: "Peter", 11 "Isabel", 9: "Anna" } +```