1

We can convert a dict into string but can we convert string back to dict ??

code

c={'a':3,'b':445}
d=str(c)

here can i replace d to type dict.

I want to take dict in form of string and encrypt all numeric digits at once using a key and retain back the dictionary with encrypted numbers.

Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113
ceasif
  • 345
  • 2
  • 14

2 Answers2

4

If I get your question right, you can achieve it this way:

>>> import ast
>>> ast.literal_eval(d)
{'a': 3, 'b': 445}
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
0

You can use json tool.

Usage of it is easy.

import json
test = {"a": 1}

# Change dict to string
json_str = json.dumps(test)
print "json_str:= ", json_str

# Change string to dict
json_obj = json.loads(json_str)
print "json_obj:= ", json_obj
umut
  • 1,016
  • 1
  • 12
  • 25
  • this doesnot work when the values associated to keys are tuple :( – ceasif May 18 '14 at 10:27
  • @ceasif you are right. It cast tuple object to list. ast.literal_eval is right way for string to dict. Thanks for the warning :). – umut May 18 '14 at 10:44