Search for mapping solution

Bengt Richter bokr at oz.net
Sun Jul 6 17:28:09 EDT 2003


On Sun, 06 Jul 2003 21:17:36 +0200, Markus Joschko <jocsch at phreaker.net> 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'}
Should same-name costs just be added, and the number just be ignored?
Assuming so, do you actually want the costs in the final dict to be represented
as localized strings, or should they be floating point numbers -- or, should they
be fixed point in effect?
>
>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.
>
If the names were all different, it would be a snap

 >>> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
 >>> d = dict([(name,cost) for name,num,cost in lines])
 >>> d
 {'sam': '1', 'fred': '0,50'}

but, your example seems to have further requirements, so maybe:

====< jocsch.py >==============================================
lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

# might want to use locale-sensitive fixed point for currency, but we'll fake it here ;-)
def str2num(s): return ',' in s and int(s.replace(',','')) or 100*int(s) # units of 0,01
def num2str(n): h,u = divmod(abs(n),100); s='-'[:n<0]; return u and '%s%d,%02d'%(s,h,u) or '%s%d'%(s,h)

d={}
for name,num,cost in lines:
    cost = str2num(cost)                            # units of 0,01
    d[name] = d.get(name, 0) + cost                 # accumulate same-name costs in integral units
for name in d.keys(): d[name] = num2str(d[name])    # mixed literal string syntax again

print lines
print d
===============================================================
Result:

[14:27] C:\pywk\clp>jocsch.py
[['fred', '333', '0,10'], ['sam', '444', '1'], ['fred', '333', '0,50']]
{'sam': '1', 'fred': '0,60'}

A uniform format (i.e., '1,00' instead of '1') would have simplified conversions a little ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list