From 367a747ad713a79e19d48814f76a26ead1d241f2 Mon Sep 17 00:00:00 2001 From: Helmut Irle Date: Sat, 10 Oct 2020 23:16:53 +0200 Subject: [PATCH 1/2] Better readability for appending to list. --- snippets/collect_dictionary.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/snippets/collect_dictionary.md b/snippets/collect_dictionary.md index d02bfefc4..85a50660e 100644 --- a/snippets/collect_dictionary.md +++ b/snippets/collect_dictionary.md @@ -5,13 +5,15 @@ 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. +- Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `collections.defaultdict`, `list()` and `append()` to create a list for each one. ```py +from collections import defaultdict + def collect_dictionary(obj): - inv_obj = {} + inv_obj = defaultdict(list) for key, value in obj.items(): - inv_obj.setdefault(value, list()).append(key) + inv_obj[value].append(key) return inv_obj ``` From 12a13d8bfbb3c9d05eab6832c5eac130fc80c811 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 11 Oct 2020 12:16:27 +0300 Subject: [PATCH 2/2] Update collect_dictionary.md --- snippets/collect_dictionary.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/snippets/collect_dictionary.md b/snippets/collect_dictionary.md index 85a50660e..d4b9112cc 100644 --- a/snippets/collect_dictionary.md +++ b/snippets/collect_dictionary.md @@ -5,7 +5,9 @@ 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 `collections.defaultdict`, `list()` and `append()` to create a list for each one. +- Create a `defaultdict` with `list` as the default value for each key. +- Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `append()`. +- Use `dict()` to convert the `defaultdict` to a regular dictionary. ```py from collections import defaultdict @@ -14,7 +16,7 @@ def collect_dictionary(obj): inv_obj = defaultdict(list) for key, value in obj.items(): inv_obj[value].append(key) - return inv_obj + return dict(inv_obj) ``` ```py