Merge pull request #335 from psyonara/better_collect_dict
Collect Dictionary: better readability when appending to list
This commit is contained in:
@ -5,14 +5,18 @@ tags: dictionary,intermediate
|
|||||||
|
|
||||||
Inverts a dictionary with non-unique hashable values.
|
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.
|
- 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
|
```py
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
def collect_dictionary(obj):
|
def collect_dictionary(obj):
|
||||||
inv_obj = {}
|
inv_obj = defaultdict(list)
|
||||||
for key, value in obj.items():
|
for key, value in obj.items():
|
||||||
inv_obj.setdefault(value, list()).append(key)
|
inv_obj[value].append(key)
|
||||||
return inv_obj
|
return dict(inv_obj)
|
||||||
```
|
```
|
||||||
|
|
||||||
```py
|
```py
|
||||||
|
|||||||
Reference in New Issue
Block a user