I have a string as this, and I want to convert it into dictionary.
test=
'{"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0}'
I tried dict(test)
but it retuned an error as:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
How can I convert this string to a dict?
CodePudding user response:
Try using ast.literal_eval
import ast
new_dict = ast.literal_eval(test)
CodePudding user response:
Your string is in JSON format, so you can use the json
module to turn it into a dict:
>>> test = '{"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0}'
>>> import json
>>> json.loads(test)
{'age': 59.0, 'bp': 70.0, 'sg': 1.01, 'al': 3.0, 'su': 0.0, 'rbc': 1.0, 'ba': 0.0, 'bgr': 76.0, 'bu': 186.0, 'sc': 15.0, 'sod': 135.0, 'pot': 7.6, 'hemo': 7.1, 'pcv': 22.0, 'wbcc': 3800.0, 'rbcc': 2.1, 'htn': 1.0, 'dm': 0.0, 'cad': 0.0, 'appet': 0.0, 'pe': 1.0, 'ane': 1.0}
>>>
Note that if you're writing a Python dictionary out as a string, you should always prefer json.dumps(data)
to str(data)
-- JSON format is portable across languages, and if you get in the habit of encoding and decoding data using common formats you're less likely to accidentally do something really bad like using eval()
for decoding. You may also sometimes find when converting data using str()
that it gets truncated for display purposes, since str()
is generally meant for printing, not for data serialization.