我有以下代碼:轉換字典字符串,字符串與dict
>>> 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
有沒有更好的解決方案。