我有以下代码:
>>> word_array = defaultdict(list)
>>> word_array['first'].append(1)
>>> word_array['first'].append(2)
>>> word_array
defaultdict(<type 'list'>, {'first': [1, 2]})
我将它转换为字符串整个数据结构,但是当我尝试从字符串转换它时我不能,我得到以下信息:
>>> ast.literal_eval(str(word_array))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
defaultdict(<type 'list'>, {'first': [1, 2]})
^
SyntaxError: invalid syntax
有没有更好的解决方案。