how to change a string into dictionary

Ulrich Eckhardt eckhardt at satorlaser.com
Mon Aug 9 06:04:45 EDT 2010


aimeixu wrote:
> a = "{'a':'1','b':'2'}"
> how to change a into a dictionary ,says, a = {'a':'1','b':'2'}

You could evaluate it as regular Python code, using "exec":

  res = {}
  exec("a={'a':'1'}", res)
  print res['a']

However, if this is input from a file or the user, be aware that this opens
loopholes for executing _any_ code, so you should only exec code from
sources you can trust.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list