How can i sum up all the kwarg value i get from cherrypy, noting that the
number of kwarg values is unknown, kwarg values are submitted from a webform kwarg values look like kwargs['asset_cost_1'] where the number incrementally starts from 1 and could go 100 or above.
the following is an example but will definitly not work and i don't think is efficient
#first determine kwargs.get('asset_cost_1') has been received
asset_cost = 0
if kwargs.get('asset_cost_1'):
for x in range(100):
kwarg = "kwargs['asset_cost_" + x + "']"
asset_cost = kwarg + asset_cost
This should do the trick:
sum(value for key, value in kwargs.items() if key.startswith('asset_cost_'))
If you want it to be ugly, you can do this:
total = 0
for key, value in kwargs.items():
if key.startswith('asset_cost_'):
total += value
And if your example was accurate, here it is as a rather dirty one liner:
sum(value for key, value in kwargs.items() if key.startswith('asset_cost_') and kwargs["asset_allocation_opex_" + key.split('_')[-1]] == "on")