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).

Some handy Python tricks, and a Python3 cheat sheet

This blog post demonstrates 10 cool Python tricks that are not covered in introductory lessons, involving tuples, lists, join, etc. I have documented some of these already here in Code Notes, but the format of the blog post is really excellent for a quick skim.

There are many Python3 cheat sheets available out there, but this one is actually clear and easy to read — unlike many others!

css.php