Emj*_*ora 0 python dictionary list
说我有一本这样的字典
D = {'a': [1,2,3], 'b': [2,3,4], 'c': [3,4,5]}
Run Code Online (Sandbox Code Playgroud)
对于所有列表中存在的每个唯一元素,我想找到相关的字典键。
因此,想要的输出是:
out = {1: ['a'], 2: ['a', 'b'], 3: ['a', 'b', 'c'], 4: ['b', 'c'], 5: ['c']}
Run Code Online (Sandbox Code Playgroud)
我如何最有效地做到这一点?
编辑:我需要为一个包含 ~100 个键的大字典和每个列表在 50-10000 个元素之间执行此操作
您可以使用collections.defaultdict:
from collections import defaultdict
out = defaultdict(list)
for k, vals in D.items():
for val in vals:
out[val].append(k)
out
# defaultdict(<class 'list'>, {1: ['a'], 2: ['a', 'b'], 3: ['a', 'b', 'c'], 4: ['b', 'c'], 5: ['c']})
Run Code Online (Sandbox Code Playgroud)
或者,使用dict.setdefault:
out = {}
for k, vals in D.items():
for val in vals:
out.setdefault(val, []).append(k)
Run Code Online (Sandbox Code Playgroud)