Can python create a dictionary from a list comprehension?

half.italian at gmail.com half.italian at gmail.com
Mon May 28 04:48:53 EDT 2007


On May 28, 12:25 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
> In <1180299814.129770.93... at o11g2000prd.googlegroups.com>, half.italian
> wrote:
>
> > [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in
> > links]
>
> > btw...I was curious of this too.  I used 'dir(dict)' and looked for a
> > method that might do what we wanted and bingo!
>
> This is really ugly.  Except `__init__()` it's always a code smell if you
> call a "magic" method directly instead of using the corresponding
> syntactic sugar or built in function.  And using a list comprehension just
> for side effects is misleading because the reader expects a (useful) list
> to be build when stumbling over a list comp and it's wasteful because an
> unnecessary list of `None`\s is build and thrown away for no reason other
> than to have a one liner.  This is not Perl!  ;-)
>
> Ciao,
>         Marc 'BlackJack' Rintsch

It's ugly I agree, but it was the first solution I found.  I need you
guys for the _right_ solutions :)  I have stumbled over the same
situation myself.  I don't see that the list comprehension itself is
misleading.  If nothing is catching the empty list that is returned,
it signals that the returned list is unimportant, and if wrapped by a
call to dict() its obvious also.

Do you think we just shouldn't use list comprehensions to build
dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?

~Sean




More information about the Python-list mailing list