0

I have a user input:

{“Alert”:3, “Beep”: 41 , “Cry”: 8}

How can I convert this to a dictionary so that I can process like one..?

I am able to do it by removing those braces and then separating each key value by splitting and so on. Is there any other simple method to do so?

bonyem
  • 1,148
  • 11
  • 20

2 Answers2

2
import ast


s = '{"Alert":3, "Beep": 41 , "Cry": 8}'

ast.literal_eval(s)
# {'Alert': 3, 'Beep': 41, 'Cry': 8}
pylang
  • 40,867
  • 14
  • 129
  • 121
2

There are couple of ways of doing it

ast.literal_eval

import ast
inp='''{"Alert":3, "Beep": 41 , "Cry": 8}'''

ast.literal_eval(inp)

json.loads

If it always follows json pattern,

import json
json.loads(inp)
{'Alert': 3, 'Beep': 41, 'Cry': 8} 
rafaelc
  • 57,686
  • 15
  • 58
  • 82