I have a dictionary with keys and values as lists. something like:
d={1:[0,1,2,3,4],2:[1,3]}
I was on the lookout for swapping key value pairs. The output I am trying to get is:
o={0:[1],1:[1,2],2:[1],3:[1,2],4:[1]}
Was wondering if there is a way to achieve this in the most efficient way
Use defaultdict:
In [30]: d={1:[0,1,2,3,4],2:[1,3]}
In [31]: from collections import defaultdict
In [32]: out = defaultdict(list)
In [33]: for k, v in d.items():
...: for vv in v:
...: out[vv].append(k)
...:
In [34]: dict(out)
Out[34]: {0: [1], 1: [1, 2], 2: [1], 3: [1, 2], 4: [1]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.