Update collect_dictionary.md

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-11 12:16:27 +03:00
committed by GitHub
parent 367a747ad7
commit 12a13d8bfb

View File

@ -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