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?

+2


source to share


3 answers


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.

+8


source


Note that you don't need it dict

in your examples: the syntax {}

gives you a dict:



dict1 = {'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]}

      

+4


source


Another way:

dict2={}
[[ (dict2.setdefault(i,[]) or 1) and (dict2[i].append(x)) for i in y ] for (x,y) in dict1.items()]  

      

-3


source







All Articles