使用ast.literal_eval将字符串转换为字典将返回ValueError:格式错误的节点或字符串

时间:2019-11-30 00:12:16

标签: python dictionary abstract-syntax-tree

我有一个格式为

的字典dict
{"value1": "{'key1.1': value1.1, ...}", 
"value2": "{'key2.1': value2.1,...}",
...}

示例(这是第一行的样子):

"NamedUser(login=""login"")","{'author': 'author', 'message_length_total': 56, 'adds_total': 2, 'subs_total': 2, 'total': 4, 'affected_files': 1, 'n_commits': 1, 'pr_msg_length_total': 1766, 'n_pr_msgs': 2, 'size_comments': 0, 'n_comments': 0, 'repo_date': 0, 'issue_length': 0, 'n_issue_opened': 0, 'n_issued_closed': 0, 'time2close': datetime.timedelta(0)}"

本质上,我键的值是用引号括起来的字典,因此被python视为字符串。

我试图遍历字典来更改它:

for i in dict:
my_string = dict[i]
dict[i] = ast.literal_eval(my_string)

但是我立即收到一个ValueError: malformed node or string错误。

其他信息: 该字典是根据csv文件创建的,其格式为:

column1, column2
key1, dictionary1
...

我现在知道这是对csv格式的错误处理,但是我无法重新格式化我的数据,并且希望按原样使用它。

那么,为什么会有这个问题,我该如何解决?谢谢。

0 个答案:

没有答案