V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2019-08-15 11:50:16 +08:00 · 1011 次点击
    这是一个创建于 1687 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    1 条回复    2019-09-03 16:14:29 +08:00
    dongxiao
        1
    dongxiao  
       2019-09-03 16:14:29 +08:00   ❤️ 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"': []}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5695 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:49 · PVG 09:49 · LAX 18:49 · JFK 21:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.