How to convert a string to a dictionary in Python
August 9, 2011 Comments
I just found out about this today while working on a Django app. I have some data stored in a database as a string but the structure is a dictionary and I wanted to retrieve it as a dictionary object.
Instead of parsing this data to retrieve the keys and values myself, it turned out Python has a module called ast (Abstract Syntax Trees) that can take care of this, specifically the literal_eval()function:
>>> import ast >>> data = "{'user': 'bob', 'age': 10, 'grades': ['A', 'F', 'C']}" >>> ast.literal_eval(data) {'age': 10, 'grades': ['A', 'F', 'C'], 'user': 'bob'} >>> user = ast.literal_eval(data) >>> user['age'] 10 >>> user['grades'] ['A', 'F', 'C'] >>> user['user'] 'bob'
Source: http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary
Tags: howto, python, django, tech, software development