简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM