views:

319

answers:

4

I've seen some Python list comprehensions before, but can this be done in a single line of Python?

errs = {}
for f in form:
    if f.errors:
        errs[f.auto_id] = f.errors
+20  A: 
errs = dict((f.auto_id, f.errors) for f in form if f.errors)
Steef
+4  A: 

It probably could be, but as per the “Readability counts.” rule (PEP 20), I'd say it's a bad idea. :)

On the other hand you have “Flat is better than nested.” and “Sparse is better than dense.”, so I guess it's a matter of taste :)

mikl
Coming from a Haskell background, I'd prefer the shorter one. I agree with you that sometimes readability is worth more, but in this particular case, my eyes hurt from seeing four lines for such a simple thing.
Deniz Dogan
I'd argue that the one-liner dict() version is more readable because it's self-documenting -- it clearly shows it's creating a dict with certain key-value pairs. The four-liner isn't bad, but it takes a bit longer to tell that it's "just creating a dict".
benhoyt
+8  A: 

Python 3.0 has dict comprehensions as a shorter/more readable form of the anser provided by Steef:

errs = {f.auto_id: f.errors for f in form if f.errors}
A: 

Both ways are quite readable, however you should think of future maintainers of the code. Sometimes explicit is better. List comprehensions rule though :)

Nick Martin