首页 > 解决方案 > 将字符串转换为 Python 字典

问题描述

此代码返回一个 str 作为类型。给定任务的格式,如何将其转换为 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))

注意:我宁愿不使用 ast.literal_eval 或 ast.eval。

标签: pythonjsondictionary

解决方案


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))

正如Barmar所说,转储将其双引号括起来

输出:

<class 'dict'>

推荐阅读