Reverse Dict in Python
I am trying to create a new dict using a list of values ββof an existing dict as separate keys.
So for example:
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
and I would like to get:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
Until now, I couldn't do it in a very clean way. Any suggestions?
source to share
If you are using Python 2.5 or higher, use a class from a module ; a automatically creates values ββthe first time a missing key is accessed, so you can use that here to create lists for , for example: defaultdict
collections
defaultdict
dict2
from collections import defaultdict
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
dict2 = defaultdict(list)
for key, values in dict1.items():
for value in values:
# The list for dict2[value] is created automatically
dict2[value].append(key)
Note that the lists in dict2 will not be in any particular order, since dictionaries do not order their key-value pairs.
If you want the usual sign to be dictated in the end, which will raise KeyError
for missing keys, just use dict2 = dict(dict2)
after the above.
source to share