Exclude 'None' from list comprehension of dicts

Weatherby,Gerard gweatherby at uchc.edu
Thu Aug 4 15:01:03 EDT 2022


Or:

data = [d for d in [get_job_efficiency_dict(job_id) for job_id in job_ids] if d is not None]

or

for job_id in job_ids:
    if (d := get_job_efficiency_dict(job_id)) is not None:
      data.append(d)


Personally, I’d got with the latter in my own code.

—
Gerard Weatherby | Application Architect NMRbox | NAN | Department of Molecular Biology and Biophysics
 UConn Health 263 Farmington Avenue, Farmington, CT 06030-6406 uchc.edu
On Aug 4, 2022, 2:52 PM -0400, MRAB <python at mrabarnett.plus.com>, wrote:
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On 2022-08-04 12:51, Loris Bennett wrote:
Hi,

I am constructing a list of dictionaries via the following list
comprehension:

data = [get_job_efficiency_dict(job_id) for job_id in job_ids]

However,

get_job_efficiency_dict(job_id)

uses 'subprocess.Popen' to run an external program and this can fail.
In this case, the dict should just be omitted from 'data'.

I can have 'get_job_efficiency_dict' return 'None' and then run

filtered_data = list(filter(None, data))

but is there a more elegant way?

I'm not sure how elegant it is, but:

data = [result for job_id in job_ids if (result :=
get_job_efficiency_dict(job_id)) is not None]
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iqxhYMoHcYQY1xohGCpafpBKZIUcGEV6Zj1-RLzOCF61TUXGr-8oh9HLuL-H8w4gxgDCypcOYOYkqNXLJxUIqhWd$


More information about the Python-list mailing list