List comprehension for dictionary – condition for adding key if value is not null

Question:

Having list comprehension of dictionaries. My goal is to create dictionary with one key if key["formula"] does not exist or dictionary with two keys if formula exists.

Currently having something like this and it works

cols = [{"header":k, **(({"formula":v["formula"]}) if v.get("formula") else {})} for k,v in inp["cols"].items()]

Is there any shorter / more elegant way to gain the same effect?

Edit (expected output): for clarification, what I need to achieve is

inp = {"cols":{"header1":{"formula":"test"}}}
cols = [{"header":k, **(({"formula":v["formula"]}) if v.get("formula") else {})} for k,v in inp["cols"].items()] 
-> 
[{'header': 'header1', 'formula': 'test'}]


inp = {"cols":{"header1":{"notformula":"test"}}}
cols = [{"header":k, **(({"formula":v["formula"]}) if v.get("formula") else {})} for k,v in inp["cols"].items()]
->
[{'header': 'header1'}]
Asked By: maliv

||

Answers:

You can improve it slightly using the dict union operator introduced in Python 3.9. Here it is with extra line breaks for readability and PEP 8 compliance.

cols = [
    {"header": k} | ({"formula": v["formula"]} if "formula" in v else {})
    for k, v in inp["cols"].items()
]

I’ve also replaced your v.get("formula") with an in check. v.get("formula") is falsy if v is {"formula": []}, for instance, which you may, but probably don’t, want.

I would consider extracting the logic on the second line into a function.

Answered By: LeopardShark
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.