Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'}]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading