-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
## Invert a python dictionary | ||
|
||
def invert_dict(d): | ||
'''Invert a dictionary | ||
values become keys, keys are inserted in a list of values | ||
This allow to store in list when somes keys initially had the same value (since keys are unique) | ||
New dict has this shape (here key1 and key2 had same value val2): | ||
val1 : [key0] | ||
val2 : [key1, key2] | ||
''' | ||
|
||
inverted_dict = {} | ||
for k, v in d.items(): | ||
inverted_dict.setdefault(v, []).append(k) | ||
return inverted_dict | ||
|
||
def invert_dict_strict(d): | ||
'''Invert a dictionary | ||
Return None if multiple keys have the same vvalue in initial dict | ||
''' | ||
|
||
if len(d) != len(set(d.values())): | ||
return None | ||
|
||
return {v: k for k, v in d.items()} |