Add collect_dictionary
This commit is contained in:
25
snippets/collect_dictionary.md
Normal file
25
snippets/collect_dictionary.md
Normal file
@ -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"] }
|
||||
```
|
||||
Reference in New Issue
Block a user