[Django]-How can this be written on a single line?

20đź‘Ť

âś…

errs = dict((f.auto_id, f.errors) for f in form if f.errors)
👤Steef

9đź‘Ť

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}
👤Steven

4đź‘Ť

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

0đź‘Ť

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

Leave a comment