2017-10-15 17 views
0

掛ける2つの辞書値、私が決めた:乗算が

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}  

しかし、どのようにこれらの辞書の値を乗算した:i場合

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) 

ラムダ式は、キーが同じであるタプル(キー、値)を作成し、値が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

ありがとう!私はdict-comprehensionで解決しようとしましたが、できませんでした。 –