推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
BryceBu
V2EX  ›  Python

str 转 dict 的小问题

  •  
  •   BryceBu · Aug 15, 2019 · 1760 views
    This topic created in 2598 days ago, the information mentioned may be changed or developed.

    现有 str: {a: {b: '值 1', c: 0, d: '值 2', e: '1', f: []}

    好像因为其中的 key 都没有引号,我用 eval() 和 ast.literal_eval() 都转换失败了

    1 replies  •  2019-09-03 16:14:29 +08:00
    dongxiao
        1
    dongxiao  
       Sep 3, 2019   ❤️ 1
    两种方式:
    方式 1:你可以先对所有 key 进行赋值,然后使用 eval
    方式 2:对 key 值进行添加引号后使用 eval (建议使用 json )

    s = "{a: 'v', b: '值 1', c: 0, d: '值 2', e: '1', f: []}"

    for ele in re.findall("(\w+)\s*:", s):
    globals()[ele] = "\"" + ele + "\""


    eval(s)
    Out[290]: {'"a"': 'v', '"b"': '值 1', '"c"': 0, '"d"': '值 2', '"e"': '1', '"f"': []}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2394 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:07 · PVG 19:07 · LAX 04:07 · JFK 07:07
    ♥ Do have faith in what you're doing.