diff --git a/snippets/collect_dictionary.md b/snippets/collect_dictionary.md new file mode 100644 index 000000000..52ed1a9db --- /dev/null +++ b/snippets/collect_dictionary.md @@ -0,0 +1,25 @@ +--- +title: collect_dictionary +tags: dictionary,intermediate +--- + +Inverts a dictionary with non-unique hashable values. + +Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `dictionary.setdefault()`, `list()` and `append()` to create a list for each one. + +```py +def collect_dictionary(obj): + inv_obj = {} + for key, value in obj.items(): + inv_obj.setdefault(value, list()).append(key) + return inv_obj +``` + +```py +ages = { + "Peter": 10, + "Isabel": 10, + "Anna": 9, +} +collect_dictionary(ages) # { 10: ["Peter", "Isabel"], 9: ["Anna"] } +```