Eval in Python 3; or, how to restore a string to a dictionary or list

One of my students scraped a website and built a CSV from the data. Inadvertently, he had some columns that appeared to contain a list of Python dictionaries. To his surprise, he found he could not read these as lists or as dictionaries directly from his CSV.

I knew that they were stored as strings, and I knew there must be a way to restore the data to its original data types. Google led me to Stack Overflow (of course), and the solution could hardly be simpler:

from ast import literal_eval
result = literal_eval(my_string)

We were then able to pluck out the value of a given dictionary key-value pair with ease.

ast is a built-in module (see docs).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.