[英]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.它们来自 excel 文件。 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.在我看来,对于这种情况,列表理解比经典循环更难理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.