How to create a dictionary/list/tuple from a string in python

Sunday, July 1, 2012

I often wondered about the easiest way to create a dictionary, tuple or a list from it's string representation in python, found out that the eval built-in function can be used to do the same, in the below example, we will see several different usages of eval command to convert a string into a dictionary, list and tuple.

Listing 1: eval.py

"""
   Create dictionaries, tuples, lists from string
   using eval built-in function
   
   Author: S.Prasanna
"""

dict_str = "{1:1, 2:2, 3:3, 4:4}"
tuple_str = "tuple(dict_obj)"
list_str = "list(dict_obj)"

print "dict_str = %s,type(dict_str) = %s" % (dict_str, type(dict_str))
print "tuple_str = %s,type(tuple_str) = %s" % (tuple_str, type(tuple_str))
print "list_str = %s, type(list(str) = %s" % (list_str, type(list_str))

dict_obj = eval(dict_str)
tuple_obj = eval(tuple_str)
list_obj = eval(list_str)

print "dict_obj = %s,type(dict_str) = %s" % (dict_obj, type(dict_obj))
print "tuple_obj = %s,type(tuple_str) = %s" % (tuple_obj, type(tuple_obj))
print "list_obj = %s, type(list(str) = %s" % (list_obj, type(list_obj))
Syntax highlighter: Pygments

Sample Output:

>>>
dict_str = {1:1, 2:2, 3:3, 4:4},type(dict_str) = <type 'str'>
tuple_str = tuple(dict_obj),type(tuple_str) = <type 'str'>
list_str = list(dict_obj), type(list(str) = <type 'str'>
dict_obj = {1: 1, 2: 2, 3: 3, 4: 4},type(dict_str) = <type 'dict'>
tuple_obj = (1, 2, 3, 4),type(tuple_str) = <type 'tuple'>
list_obj = [1, 2, 3, 4], type(list(str) = <type 'list'>
>>>

No comments:


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.