I have the following code:
>>> word_array = defaultdict(list)
>>> word_array['first'].append(1)
>>> word_array['first'].append(2)
>>> word_array
defaultdict(<type 'list'>, {'first': [1, 2]})
I converted it to string the whole data structure, but when i try to convert it from string i can’t, i get the following:
>>> 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
Is there any better solution to this.
All you want to do here is serialize your data structure into a string, and then deserialize it back into a data structure. Don’t use things like
ast.literal_evalin production. Just usepickle:Gives: