[Tutor] Tutor] Careful Dictionary Building

doug shawhan doug.shawhan at gmail.com
Fri Dec 28 19:14:38 CET 2007


Lots of very good answers to a pretty stupid question! *blush*

I guess there is more than one way to do it!

Uh ... guys? Did I say something wrong...?

<sounds of a thorough beating with a haddock>

On Dec 28, 2007 12:23 PM, Tony *** <****@gmail.com> wrote:

> Hello Doug,
>
> You can also use exceptions instead of the if /else. It has more of a
> pythonic syntax to it, but I'm not sure about performance.
>
> try:
>    dict[ record[0] .append( record ) ]
> except:KeyError
>
>     dict[ record[0] ] = [record]
>
>
> To help performance a bit, don't call dict.keys() on every iteration,
> since you're invoking a function.
>
> dict = {}
> allKeys =dict.Keys
> for record in list
>   if record[0] in allKeys:
>       dict[ record[0] .append( record ) ]
>   else:
>       dict[ record[0] ] = [record]
>       allKeys = dict.Keys()                    # this function is
> only invoked some of the time, not on every iteration
>
>
> See how much this helps your performance. It  may not be much, but a
> little can help
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/ca803ce4/attachment.htm 


More information about the Tutor mailing list