-1

I am trying to convert the following string into list. However I get the variable enclosed in round brackets.

a = '{"0": "407-1656"}, {"4": "512-873"}'

b = [a]

on executing above following is the value of b

['{"0": "407-1656"}, {"4": "512-873"}']

I require the output to be

[{"0": "407-1656"}, {"4": "512-873"}]

Thanks.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • 2
    There are at least a couple of simple ways of doing this. but if you are having trouble working with square brackets, what you really need is an introductory Python tutorial. – Mad Physicist Nov 05 '17 at 05:29
  • @MadPhysicist pretty sure he is trying to remove the quotes.. i think he is trying to convert his string into a list of dictionaries – 0TTT0 Nov 05 '17 at 05:32
  • @0TTT0. I understand what he is trying to do, my issue is with the lack of any real attempt to solve the problem. – Mad Physicist Nov 05 '17 at 05:37
  • @MadPhysicist I have tried a couple of things and have also searched sites with specific issue but no success. tried eval command and tried coverting it to list directly. – muffazel Nov 05 '17 at 05:43
  • 1
    hey @muffazel `b = [eval(c) for c in a.split(',')]` – 0TTT0 Nov 05 '17 at 06:01

1 Answers1

3

You can use ast.literal_eval()

>>> from ast import literal_eval
>>> b = literal_eval(a)
>>> b
({'0': '407-1656'}, {'4': '512-873'})
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57