-1

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])
khelili miliana
  • 3,730
  • 2
  • 15
  • 28

2 Answers2

0

The list of dict contains taxes has only two values. You can use a dict instead of list. Rebuild your list of taxes to dict of taxes, which use name as key

taxes_dict = {}
for tax in taxes:
    taxes_dict[tax['name']] = tax

So you can calculate the tva in one line so:

sum([t[amount]*t[qty]*taxes_dict['tva']['amount'] if 'tva' in t['tax'] else 0 for t in products])

P/S: please check your list again. name, qty and tax should may be 'name', 'qty' and 'tax'

qvpham
  • 1,896
  • 9
  • 17
0

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'])
khelili miliana
  • 3,730
  • 2
  • 15
  • 28