美文网首页
python如何将字符串转换成字典dict类型

python如何将字符串转换成字典dict类型

作者: caoxinyiyi | 来源:发表于2018-07-23 11:40 被阅读5次

    用eval()或exec()函数实现,本人习惯于用eval()

    >>> user = "{'name' : 'jim', 'sex' : 'male', 'age': 18}"
    >>> user['name']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: string indices must be integers, not str
    >>> b = eval(user)
    >>> b
    {'age': 18, 'name': 'jim', 'sex': 'male'}
    >>> b['name']
    'jim'
    >>> exec("c="+user)
    >>> c
    {'age': 18, 'name': 'jim', 'sex': 'male'}
    >>> c['age']
    18
    >>>
    

    注意:这种方式要注意风险,因为eval实际上是解释执行python代码,如果输入来源于外部....,所以使用的使用要谨慎。

    相关文章

      网友评论

          本文标题:python如何将字符串转换成字典dict类型

          本文链接:https://www.haomeiwen.com/subject/xxgdmftx.html