Search for mapping solution

Max M maxm at mxm.dk
Sun Jul 6 15:51:04 EDT 2003


Markus Joschko wrote:

> Hi,
> stated in a post befor, I'm a java programmer, fascinated about the elegant
> way python solves iterations. Maybe you can show me a solution how to map
> the following
> 
> I have a List:
> 
> Name - Number - Costs
> 
> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
> 
> Now I want to have it in a dictionary(name,costs)  Should look like
> {'fred':'0,60' , 'sam':'1'}
> 
> What's an elegant way to do it? I can use a lot of loops, but I assume, that
> there is a better way of doing so.

lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
costs = {}
for name, items, price in lines:
     costs[name] = costs.setdefault(name, 0.0) + 
float(price.replace(',','.'))

print costs

 >>> {'fred': 0.59999999999999998, 'sam': 1.0}

regards Max M
	





More information about the Python-list mailing list