Yaroslav
Yaroslav

Reputation: 97

Creation of nested dictionaries from other dictionaries

I can create a complex dictionary by making a dictionary from the list of values with a value added to the list:

NEED=  {'need1': ['good1', 'good2'], 'need2': ['good2', 'good3']}
DM= {'good1': 1, 'good2': 1, 'good3': 10}

NG = {
    n_key: [
        {n_ch_key: DM[n_ch_key] for n_ch_key in n_l}
    ] 
    for n_key, n_l in NEED.items()
} 
OUT:{'need2': [{'good2': 1, 'good3': 10}], 'need1': [{'good2': 1, 'good1': 1}]}

But how to create a dictionary like this:

IN: CN= {'need1': 3, 'need2': 2}
    NEED= {'need1': ['good1', 'good2'],'need2': ['good2', 'good3'] }

OUT: NG={'need1': [{'good1': 3, 'good2': 3}], 'need2': [{'good2': 2, 'good3': 2}]}

Upvotes: 1

Views: 26

Answers (1)

Louis R
Louis R

Reputation: 1790

Nothing really more complex than what you just wrote :

NG = {
    n_key: [
        {n_ch_key: CN[n_key] for n_ch_key in n_l}
    ] 
    for n_key, n_l in NEED.items()
}

Upvotes: 1

Related Questions