I am trying to create a new dict using a list of values of an existing dict as individual keys.
So for example:
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
and I would like to obtain:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
So far, I’ve not been able to do this in a very clean way. Any suggestions?
If you are using Python 2.5 or above, use the
defaultdictclass from thecollectionsmodule; adefaultdictautomatically creates values on the first access to a missing key, so you can use that here to create the lists fordict2, like this:Note that the lists in dict2 will not be in any particular order, as a dictionaries do not order their key-value pairs.
If you want an ordinary dict out at the end that will raise a
KeyErrorfor missing keys, just usedict2 = dict(dict2)after the above.