使用'dict-comprehension'和'for in'和'if',用两个不同的'dicts'来'列出''值'的'值'

时间:2017-08-16 18:40:15

标签: python-3.x list dictionary dictionary-comprehension

例如,给出了两个词典:NEED和DG。

需要创建一个新的'dict'(NDE),其中新的'keys'将与NEED中的相同,并且新的'values'(NDE)将对应于'list'与嵌套的DG字典,其“键”对应于(NEED)中的“值”,以及“值” - 来自DG的“值”。

In: NEED=  {'need1': ['good1', 'good2'], 'need2': ['good2']}
    DG= {'good1': '20', 'good2': '15'}

Out: NDE={'need1':[{'good1': '20', 'good2': '15'}], 'need2': [{'good2': '15'}]}

2 个答案:

答案 0 :(得分:0)

当尝试使用列表或字典理解时,我通常尝试使用普通for loop来解决问题,因为逻辑往往更简单一些。在这种情况下,一系列循环看起来像:

NEED = {'need1': ['good1', 'good2'], 'need2': ['good2']}
DG = {'good1': '20', 'good2': '15'}

NDE = {}
for need_key, need_list in NEED.items():
    sub_dict = {}
    for need_child_key in need_list:
        sub_dict[need_child_key] = DG[need_child_key]

    NDE[need_key] = [sub_dict]

一旦我无法理解它,我就开始处理理解部分。

NDE = {
    need_key: [
        {need_child_key: DG[need_child_key] for need_child_key in need_list}
    ] 
    for need_key, need_list in NEED.items()
}

注意:我的解决方案假设NEED中的值始终对应于DG ...

中的键

答案 1 :(得分:0)

<强> CODE:

NEED = {'need1': ['good1', 'good2'], 'need2': ['good2']}
DG = {'good1': '20', 'good2': '15'}

NDE={}
for i in NEED.keys(): #initializing nested dict
    NDE[i] = {}

for i in NEED.keys():
    for j in DG.keys():
        for k in NEED[i]:
            if k==j:
                NDE[i][j] = DG[j]

print(NDE)

<强>输出:

{'need1': {'good1': '20', 'good2': '15'}, 'need2': {'good2': '15'}}