2017-10-15 90 views
0

乘法两本字典,我决定如下:乘积值

n1={'number1': '200', 'number2': '100'} 
n2={'number1': '2', 'number2': '1'} 

total = lambda dct_1, dct_2: {key: int(dct_2[key]) * int(dct_1[key]) for key in dct_2} 

total (n1, n2) 
# Out: {'number1': 400, 'number2': 100}  

但如何乘值这些词典:

IN: NG={'need1': [{'good2': 2, 'good3': 2}], 'need2': [{'good2': 3, 'good1': 3}]} 
    G= {'good1': 10, 'good2': 30, 'good3': 40} 


# OUT:{'need1': [{'good2': 60, 'good3': 80}], 'need2': [{'good2': 90, 'good1': 120}]} 

回答

1

下得到正确的结果,如果我理解这个问题。

NG={'need1': [{'good2': 2, 'good3': 2}], 'need2': [{'good2': 3, 'good1': 3}]} 
G= {'good1': 10, 'good2': 30, 'good3': 40} 


for a, b in NG.items(): # iterate over (key,value)'s 
    new = [] 
    for c in b: # iterate over values 
     z = map(lambda w: (w[0], w[1]*G[w[0]]), c.items()) 
     new.ppend(dict(z)) # add dict to new value 
    NG[a] = new # update value 

print(NG) 

Lambda表达式创建的元组(关键字,值),其中所述键是相同的,并且该值为value*G[key]

map(lambda w: (w[0], w[1]*G[w[0]]), c.items()) 

这些被保存在new中,它替换了旧密钥的值。

输出:

{'need1': [{'good2': 60, 'good3': 80}], 'need2': [{'good2': 90, 'good1': 30}]} 
+0

感谢您的解决方案!我试图用字面理解来解决它,但我不能。 –