使用 "comprehension" 和 python3 中的条件 "If" 创建字典

Creating dict using "comprehension" and the condition "If" in python3

例如,给定一个'dictionary'(NE),其中'keys'是需求,价值是满足这些需求的商品'list'。 How to create a new 'dictionary' (NG) using dict-comprehension, which new 'keys' - will be goods from (NE), new 'values' - 'list' 的来自 (NE) 的需求,这些产品正在得到满足。

In: NE={'need1': ['good1', 'good2', 'good3'], 'need2': ['good2'], 'need3': ['good1', 'good4']}

Out: NG={'good1': ['need1', 'need3'], 'good2': ['need1', 'need2'], 'good3': ['need1'], 'good4': ['need3']}

这可行,但不是很漂亮

{good:[need for need in NE if good in NE[need]] for need, goods in NE.items() for good in goods}

如果没有人找到更好的解决方案,我认为你不能使用字典理解