[Tutor] Tutor] Careful Dictionary Building
Kent Johnson
kent37 at tds.net
Fri Dec 28 20:28:06 CET 2007
doug shawhan wrote:
> To help performance a bit, don't call dict.keys() on every iteration,
> since you're invoking a function.
>
> dict = {}
> allKeys =dict.Keys
Should be dict.keys()
> for record in list
> if record[0] in allKeys:
> dict[ record[0] .append( record ) ]
Should be
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
So you only create the list of keys when it changes; that may speed up
the loop, depending on how many duplicates there are. But there are two
big problems with the original program - it creates a new list of keys
each time through the loop, and it searches for a key in the list
instead of looking it up directly in the dict. Your change may cut down
on the number of times the key list is created but it will not improve
the search time at all.
In other words, you are making modest improvements to a broken
algorithm; a better fix is to use a better algorithm.
Kent
More information about the Tutor
mailing list