Python 使用列表形式的值交换字典中的键值对

Python 使用列表形式的值交换字典中的键值对,python,Python,我有一本以键和值为列表的字典。比如: d={1:[0,1,2,3,4],2:[1,3]} 我一直在寻找交换键值对的方法。我试图获得的输出是: o={0:[1],1:[1,2],2:[1],3:[1,2],4:[1]} 我想知道是否有最有效的方法来实现这一点使用defaultdict: In [30]: d={1:[0,1,2,3,4],2:[1,3]} In [31]: from collections import defaultdict In [32]: out = defaultdi

我有一本以键和值为列表的字典。比如:

d={1:[0,1,2,3,4],2:[1,3]}
我一直在寻找交换键值对的方法。我试图获得的输出是:

o={0:[1],1:[1,2],2:[1],3:[1,2],4:[1]}
我想知道是否有最有效的方法来实现这一点

使用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]}

如果您做得正确,就不可能得到索引错误,因为您正在迭代元素而不是索引。