Import string as Dictionary in Python

I had a Python dictionary (that looks like json) stored in a file, generated by some code. Now I wanted it in Python to act as the dictionary. But when we read that file, it gets stored as string (in a variable). But I wanted to access its keys and values. But if it’s a string we couldn’t do this directly.

So I searched for a method to convert string to dict. Here is the go:

In [1]: import ast

In [2]: string = “{‘name’: ‘xyz’, ‘age’: 3}”

In [3]: string
Out[3]: “{‘name’: ‘xyz’, ‘age’: 3}”

In [4]: ast.literal_eval(string)
Out[4]: {‘age’: 3, ‘name’: ‘xyz’}

In [5]: the_dict = ast.literal_eval(string)

In [6]: the_dict.keys()
Out[6]: [‘age’, ‘name’]



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s