KHELILI Hamza KHELILI Hamza - 1 year ago 75
Python Question

Calculate TVA Tax of multiple product in one code line (python)

I've a list of dict contains products :

products = [{'name' : 'art1','amount':2000, 'qty':2, 'tax':['tax_15', 'tva']} ,
{'name' : 'art2','amount':2500, 'qty':3, 'tax':['tax_15', 'timbre']},
{'name' : 'art3','amount':3000, 'qty':4, 'tax':['tva']}]

and a list of dict contains taxes :

taxes = [{'name' : 'tax_15','amount':15} ,
{'name' : 'tva','amount':17},
{'name' : 'timbre','amount':10}]

I want to calculate tva of all products, in this exemple, tva exists just in art1 and art3, in this case:

tva = (2000 * 17%) + (3000 * 17%)

I want to calculate the tva in one single line of python code, I tried with this line:

sum([t['amount']*t['qty']*tax_of_tva_if_exist_in_this_product for t in products])

Answer Source

After hard search, I find the response :

sum([item['amount']*tax['amount'] for item in products if 'tva' in item['tax'] for tax in taxes if tax['name']=='tva'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download