1

I got a string, it's like:

"{'a': 1, 'b': 2, 'c': 3}"

I want to assign a variable to this string and make the variable a dict. It sounds easy, but I spend half hour and didn't figure it out. How to do it?

5
  • 1
    How do you get this string? Jun 15, 2014 at 8:30
  • @thefourtheye, some result passed by other colleagues, this is a rather abstract form.
    – Zen
    Jun 15, 2014 at 8:31
  • 1
    Can't you ask them to pass the data as key-value pairs? Jun 15, 2014 at 8:32
  • Why aren't they just giving you the dict that you want? Jun 15, 2014 at 8:36
  • @KarlKnechtel, It's writing in a file, every item has a stinged dict
    – Zen
    Jun 15, 2014 at 10:18

1 Answer 1

8

Use the ast.literal_eval() function as follows:

>>> import ast
>>> ast.literal_eval("{'a': 1, 'b': 2, 'c': 3}")
{'a': 1, 'b': 2, 'c': 3}

You could use it in a programme as follows:

import ast
dictString = "{'a': 1, 'b': 2, 'c': 3}";
dictFinal = ast.literal_eval(dictString)
print (dictFinal)

There is more help in the docs at this link

2
  • 3
    probably better not using dict as a variable name. Jun 15, 2014 at 8:34
  • ahh right, was just coding off the top of my head
    – Morgoth
    Jun 15, 2014 at 8:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.