【问题标题】:How to convert a dictionary that is in string form into dictionary form in python?如何将字符串形式的字典转换为python中的字典形式?
【发布时间】:2022-11-10 23:43:56
【问题描述】:

我有一个这样的字符串,我想把它转换成字典。

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}'

我试过dict(test),但它返回了一个错误:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

如何将此字符串转换为字典?

【问题讨论】:

    标签: python python-3.x dictionary data-structures


    【解决方案1】:

    尝试使用ast.literal_eval

    import ast
    
    new_dict = ast.literal_eval(test)
    

    【讨论】:

      猜你喜欢
      • 2010-11-02
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2011-05-06
      • 2019-12-05
      相关资源
      最近更新 更多