Files
30-seconds-of-code/snippets/collect_dictionary.md
Isabelle Viktoria Maciohsek ecc35f200b Add collect_dictionary
2020-04-07 21:15:06 +03:00

26 lines
593 B
Markdown

---
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"] }
```