Dictionary question

Nick Vatamaniuc vatamane at gmail.com
Tue Jul 18 08:11:17 EDT 2006


Brian,
You can try the  setdefault method of the dictionary.
For a dictionary D the setdefault work like this:
D.setdefault(k, defvalue). If k not in D then D[k] is set to defvalue
and defvalue is returned.
For example:
In [1]:  d={}
In [2]:  d.setdefault(1,5)
Out[2]:5
In [3]:  d
Out[3]:{1: 5}
In your case you could do something like:

if l[-1].setdefault(a+c, x+e)<x+e:
    l[-1][a+c]=x+e

If a+c not in l[-1] then it the if ... line will set it to x+e and x+e
will be returned, obviously the if ... will fail and the execution will
go on after the if block. If a+c is in l[-1] then if will compare
l[-1][a+c] to x+e.

Also for clarity you might actually want to assign some variables to
a+c and x+e since you repeat them so often. That actually might speed
up your code a little too, but don't do it just for a minor speedup do
it for clarity and simplicity most of all!

Good luck,
Nick Vatamaniuc


Brian Elmegaard wrote:
> Brian Elmegaard <brian at rkspeed-rugby.dk> writes:
>
> At least it was clumsy to post a wrong example.
> This shows what = find clumsy.
>
> c=1
> x=2
>
> l=list()
> l.append(dict())
> l[0][5]=0
>
> l.append(dict())
>
> 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
> #########
>
> print l
>
>
> > Hi
> >
> > I have written the following which works, but I would like to write it
> > less clumsy. I have a dictionary in which I loop through the keys for
> > a dynamic programming algorithm. If a key is present I test if its
> > value is better than the current, if it is not present I just create
> > it. Would it be possible to write it more compact?
> >
> > ###############3
> > c=1
> > s=8
> > x=2
> >
> > l=list()
> > l.append(dict())
> > l[0][5]=0
> >
> > l.append(dict())
> >
> > for a, e in l[-2].iteritems():
> >     if a+c<s: ##### Can this improved?
> >         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 #####
> > print l
> > #####################
> >
> > tia,
> > --
> > Brian (remove the sport for mail)
> > http://www.et.web.mek.dtu.dk/Staff/be/be.html
> > Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk
>
> --
> Brian (remove the sport for mail)
> http://www.et.web.mek.dtu.dk/Staff/be/be.html
> Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk




More information about the Python-list mailing list