Why does one work, but not the other?

Robert Brewer fumanchu at amor.org
Fri Jun 18 16:59:57 EDT 2004


j_mckitrick wrote:
> 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)

My usual solution to that is generically written:

dict([(k, v) for k, v in d.iteritems()])

...taking advantage of the fact the you can pass dict() a list of
tuples. Your specific example would be written:

db = dict([(k, str(v)) for k, v in self.options.iteritems()])

I use iteritems more often, since it doesn't create an intermediate
structure.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org

P.S. Where is everyone on c.l.p. today? Brother Ray's memorial...?




More information about the Python-list mailing list