Dictionary question

John Machin sjmachin at lexicon.net
Tue Jul 18 08:27:13 EDT 2006


On 18/07/2006 9:51 PM, 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?

Definitely.
1. Use meaningful names. Especially don't use 'L'.lower() as it's too 
easily confused with the digit '1'.
2. Put spaces around operators -- in general, RTFStyleGuide 
http://www.python.org/dev/peps/pep-0008
3. When you find yourself typing the same expression 4 times, it's time 
to give it a name of its own (or to throw away a usage or two).


>     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

Here's a start. Only you know what *really* meaningful names you should 
be using.

mykey = a + c
newvalue = x + e
lastdict = dictlist[-1]
if mykey not in lastdict or lastdict[mykey] < newvalue:
     lastdict[mykey] = newvalue

4. Add some comments about what you are trying to achieve. What is the 
point of keeping the two dicts in a list??? Can't you give them names, 
like rawdatadict and maxdict?

HTH,
John



More information about the Python-list mailing list