Why does one work, but not the other?

Peter Otten __peter__ at web.de
Fri Jun 18 13:36:45 CEST 2004


j_mckitrick wrote:

> But I'm still on my mission to replace 'for' with list comprehensions
> where possible, according to the article on optimization on the python
> site.

I don't know the article, but I assume it doesn't tell list comprehensions
are always faster/better. 
 
> That being said, is there a way to write this as a comprehension?  I
> can't figure out how to do so and get k into the key correctly.  I'm
> just trying to save a dictionary via anydbm.
> 
>             for k, v in self.options.items():
>                 db[k] = str(v)

Yes,

>>> dk = {1:2, 3:4}
>>> options = {1:4, 2:6, 3:8}
>>> dk.update(dict([(k, str(v)) for (k, v) in options.iteritems()]))
>>> dk
{1: '4', 2: '6', 3: '8'}
>>>

but why would you trade a muddy comprehension for a clean loop? The for loop
is clearer (and faster, I suppose) here. Remember that list comprehensions
are a means rather than an end.

With 2.4 that may be a different story, as the above will reduce (I think)
to

dk.update((k, str(v)) for (k, v) in options.iteritems())

However, some overhead (generating throwaway tuples) is likely to remain.

Peter




More information about the Python-list mailing list