Skip to content

Commit

Permalink
invert dict
Browse files Browse the repository at this point in the history
  • Loading branch information
Pullusb committed Oct 25, 2023
1 parent 1d428fc commit 258f893
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions snippets/py/invert_dictionary.py
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()}

0 comments on commit 258f893

Please sign in to comment.