有效地交换python dict的键和值,其中值包含一个或多个元素

lf2*_*215 2 python algorithm dictionary

假设我有一个词典:

x =  { "a": ["walk", "the", "dog"], "b": ["dog", "spot"], "c":["the", "spot"]  }
Run Code Online (Sandbox Code Playgroud)

并希望有新的词典:

y = { "walk": ["a"], "the": ["a", "c"], "dog":["a", "b"], "spot":["b","c"]  }
Run Code Online (Sandbox Code Playgroud)

最有效的方法是什么?如果一个解决方案是几行并且通过pythonic构造以某种方式简化它是什么(即使它不是最有效的)?

请注意,这与其他问题不同,其中值是单个元素而不是列表.

Ble*_*der 5

你可以使用defaultdict:

from collections import defaultdict

y = defaultdict(list)

for key, values in x.items():  # .iteritems() in Python 2
    for value in values:
        y[value].append(key)
Run Code Online (Sandbox Code Playgroud)