我可以通过从值列表中创建一个字典来创建一个复杂的字典,并将值添加到列表中:
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}]}
但是如何创建这样的字典:
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}]}
答案 0 :(得分:1)
没有什么比你刚写的更复杂:
NG = {
n_key: [
{n_ch_key: CN[n_key] for n_ch_key in n_l}
]
for n_key, n_l in NEED.items()
}