I believe the best way is to simply loop as you did:
target = defaultdict(list)
for key, values in original.items():
for value in values:
target[value].append(key)
Alternatively you could avoid the inner for
:
for key, values in original.items():
target.update(zip(values, [key] * len(values)))
Or using itertools.repeat
:
import itertools as it
for key, values in original.items():
target.update(zip(values, it.repeat(key)))
However these last solutions only work for the simple case where values in different lists are distinct.
Remember that pythonic doesn't have any definite meaning. I'd consider python a solution that is:
- Readable
- Correctly use the language features
- Correctly use the built-ins/standard library
- Efficient
And the points are in order of importance. Efficience is last because it is most often implied by point 2 and 3.