简体   繁体   English

将字符串转换为 Python 字典

[英]Converting String to Python Dictionary

This code returns a str as the type.此代码返回一个 str 作为类型。 Given the format of tasks, how do I convert it into a python dictionary?鉴于任务的格式,如何将其转换为 python 字典?

import json

tasks = '''{'key1': 'val1', 'key2': None}'''

new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')

new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))

Note: I would prefer to not use ast.literal_eval or ast.eval.注意:我不想使用 ast.literal_eval 或 ast.eval。

import json

tasks = '''{'key1': 'val1', 'key2': None}'''

new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')

# new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))

As Barmar said, the dumps double wraps it in quotation marks正如 Barmar 所说,转储用引号将其双包裹

output:输出:

<class 'dict'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM