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

Use Dict Comprehension to modify Values that contain lists

How might I refactor this loop into a Dict Comprehension? Should I?

for key,val in myDict.items():
    if '[' in val:
        myDict[key] = (ast.literal_eval(val)) 

For context, some of the values in the dictionary are lists, but formatted as strings; they come from an excel file. Anytime ‘[‘ is encountered in a cell, I want the dictionary value to be the literal cell value, not a string of it.

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

>Solution :

Do you want something like this?

{key: ast.literal_eval(val) if '[' in val else val for key, val in myDict.items()}

In my opinion, for this case List Comprehension is less understandable than classic loop.

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