Dictionary question

Justin Azoff justin.azoff at gmail.com
Tue Jul 18 08:23:31 EDT 2006


Brian Elmegaard wrote:
> for a, e in l[-2].iteritems():
> ######### Can this be written better?
>     if a+c in l[-1]:
>         if l[-1][a+c]<x+e:
>             l[-1][a+c]=x+e
>     else:
>         l[-1][a+c]=x+e
> #########

I'd start with something like

for a, e in l[-2].iteritems():
    keytotal  = a+c
    valtotal  = x+e
    last      = l[-1]
    if keytotal in last:
        if last[keytotal] < valtotal:
            last[keytotal] = valtotal
    else:
        last[keytotal] = valtotal

Could probably simplify that even more by using min(), but I don't know
what kind of data you are expecting....
last[keytotal] = min(last.get(keytotal), valtotal)
comes close to working - it would if you were doing max.


-- 
- Justin




More information about the Python-list mailing list