Can I build a dictonary with a list-comprehension?

Andrew Dalke dalke at dalkescientific.com
Mon Sep 3 19:16:44 CEST 2001


spex66:
>found in PLEAC (pleac.sourceforge.net)
 ...
>[dict.update({x: 'spam'}) for x in LIST]
 ...
>thx PLEAC project!

Marcin 'Qrczak' Kowalczyk:
>Using list comprehensions when the result is ignored is misleading
>and inefficient. A for loop is better.

Indeed.  Here's the most relevant PLEAC secion, 4.7, including
the comment that spex66 elided:

-----
seen = {}   # lookup table
aonly = []  # answer

# build lookup table - NOTE: this is poor Python style
[seen.update({x: 1}) for x in B]
 -----

and occuring after a subsection which shows a more typically
Python way do to it:

for item in B:
    seen[item] = 1

I wrote that section of PLEAC, so I can describe why it's
written that way.  The original Perl code shows different
ways to do the same task, varying from easy to understand
to dense, idiomatic Perl.  Section 4.7 included multiple
subsections.  The first has

 ----
foreach $item (@B) { $seen{$item} = 1 }
 ----

(which was directly translated to a Python loop) and the
second has

 ----
# build lookup table
@seen{@B} = ();
 ----

I decided to try to translate this latter one to something
more terse, to show that there are other ways to do things
in Python, but to note that the usage was uncommon.

PLEAC does have a problem in that the original code is
meant to show off Perl, so parts of it don't translate
well to other languages.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list