Python convert string to list/tuple/dictionary

By using ast modules literal_eval function we can convert any python string to valid literal.

ast modules literal_eval function will only evaluates string that are valid python literals.

Lets try with an example:

I have file with some valid python literals and I want to evaluate each of them.

Content of my input file is following:

[1, 2, 3]
(1, 2, 3)
{‘a’:1, ‘b’:2, ‘c’:3}
‘abc’
123

Here I want to detect type of literal in each line.

First I will try with a simple example:

#!/usr/bin/python
import os, sys
f = open(sys.argv[1], 'r')
lines = f.readlines()
print lines
for i in lines:
    print i.strip(), type(i)

Output:

[1, 2, 3] <type ‘str’>
(1, 2, 3) <type ‘str’>
{‘a’:1, ‘b’:2, ‘c’:3} <type ‘str’>
‘abc’ <type ‘str’>
123 <type ‘str’>

Just observer output, by default all lines are detected as string.

Now try with ast modules literal_eval function.

#!/usr/bin/python
import os, sys, ast
f = open(sys.argv[1], 'r')
lines = f.readlines()
#print lines
for i in lines:
    print i, type(ast.literal_eval(i))

Output:

[1, 2, 3] <type ‘list’>
(1, 2, 3) <type ‘tuple’>
{‘a’:1, ‘b’:2, ‘c’:3} <type ‘dict’>
‘abc’ <type ‘str’>
123 <type ‘int’>

Now observer above output, each line is detected and converted as its own literal type.

I tested this example in Python 2.7.3

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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