zoukankan      html  css  js  c++  java
  • python str转dict

    两种方法


    eval(str)

    >>> user = "{'name' : 'jim', 'sex' : 'male', 'age': 18}"
    >>> type(user)
    <type 'str'>
    >>> b=eval(user)
    >>> 
    >>> b
    {'age': 18, 'name': 'jim', 'sex': 'male'}
    >>> type(b)
    <type 'dict'>

    关于eval()的说法,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。
    实际上这是有局限的,例如处理多维字典就不行了

    json
    另一种专业的转换工具是json

    >>> user = '{"name":"jim","sex":"male","age":"18"}'
    >>> json.loads(user)
    {u'age': u'18', u'name': u'jim', u'sex': u'male'}
    >>> type(user)
    <type 'str'>
    >>> type(json.loads(user))
    <type 'dict'>

  • 相关阅读:
    【POJ 2778】DNA Sequence
    【POJ 2923】Relocation
    codeforces 475D
    hdu4742
    hdu4741
    hdu5016
    poj3929
    Codeforces Round #267 (Div. 2)
    codeforces 455E
    hdu4073 Lights
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14255969.html
Copyright © 2011-2022 走看看