loop beats generator expr creating large dict!?

Ant antroy at gmail.com
Tue Oct 3 11:05:43 CEST 2006


George Young wrote:
...
> I am puzzled that creating large dicts with an explicit iterable of
> key,value pairs seems to be slow.  I thought to save time by doing:
>
>    palettes = dict((w,set(w)) for w in words)
>
> instead of:
>
>    palettes={}
>    for w in words:
>       palettes[w]=set(w)

In the generator case, you are first creating a tuple, and then
assigning the first element of the tuple as the key and the second
element as the value in the dictionary. In the loop, you are directly
setting the key and value in the dictionary.

Essentially by doing the generator (or comprehension), you are packing
and unpacking the key, value pairs for each word in your initial list,
all of which will have an overhead.




More information about the Python-list mailing list