复数字典值的乘法

时间:2017-10-15 16:46:56

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

两个词典相乘,我决定如下:

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 个答案:

答案 0 :(得分: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}]}