Re: how to change a string into dictionary

2010-08-09 Thread Shashwat Anand
On Mon, Aug 9, 2010 at 3:03 PM, aimeixu aime...@amazon.com wrote:

 Hi,
 I am newbie for python ,Here is my question:
 a = {'a':'1','b':'2'}
 how to change a into a dictionary ,says, a = {'a':'1','b':'2'}
 Thanks a lot .Really need help.


Parse the string and re-create the dictionary.

 s = {'a':'1','b':'2'}
 ds = {}
 for i in s.strip('{}').split(','):
... key, val = i.split(':')
... ds[key.strip(')] = val.strip(')
...
 ds
{'a': '1', 'b': '2'}
 type(ds)
class 'dict'


  --
 http://mail.python.org/mailman/listinfo/python-list




-- 
~l0nwlf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change a string into dictionary

2010-08-09 Thread Chris Rebert
On Mon, Aug 9, 2010 at 2:53 AM, Shashwat Anand anand.shash...@gmail.com wrote:
 On Mon, Aug 9, 2010 at 3:03 PM, aimeixu aime...@amazon.com wrote:
 Hi,
 I am newbie for python ,Here is my question:
 a = {'a':'1','b':'2'}
 how to change a into a dictionary ,says, a = {'a':'1','b':'2'}
 Thanks a lot .Really need help.

 Parse the string and re-create the dictionary.
 s = {'a':'1','b':'2'}
 ds = {}
 for i in s.strip('{}').split(','):
 ...     key, val = i.split(':')
 ...     ds[key.strip(')] = val.strip(')

Just for the record, that'll break if the dictionary entries have
embedded commas or colons.
eval() will handle such cases correctly and probably* run faster, but
is obviously insecure.

If you have control of both ends of the serialization process, you
might consider using the `json` or `pickle` std lib modules instead.

Cheers,
Chris
--
*Do a benchmark obviously.
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change a string into dictionary

2010-08-09 Thread Ulrich Eckhardt
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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change a string into dictionary

2010-08-09 Thread Daniel Urban
 a = {'a':'1','b':'2'}
 how to change a into a dictionary ,says, a = {'a':'1','b':'2'}

See also the ast.literal_eval function:
http://docs.python.org/py3k/library/ast.html#ast.literal_eval


Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list