Search code examples
python-3.xdictionarylist-comprehensiondictionary-comprehension

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


For example, a 'dictionary' (NE ) is given in which 'keys' are needs, and values are 'list' of goods to meet these needs. How to create a new 'dictionary' (NG) using dict-comprehension, in which new 'keys' - will be goods from (NE), and new 'values' - a 'list' of needs from (NE), that these products are being satisfied.

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

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

Solution

  • This works but isn't very pretty

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

    If nobody find a better solution i think that you musn't use dict comprehension