【问题标题】:Python - How to convert dictionary alike string to dictionary [duplicate]Python - 如何将类似字典的字符串转换为字典[重复]
【发布时间】:2020-10-23 16:30:18
【问题描述】:

我有一个字符串如下

"{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}"

我怎样才能真正将这个字符串转换为字典?字符串来源于一个txt文件

【问题讨论】:

标签: python


【解决方案1】:

您应该使用 json 模块。您可以打开文件并使用json.load(file) 或将文本作为字符串包含在程序中并执行json.loads(text)。例如:

import json

with open('file.txt', 'r') as file:
    dict_from_file = json.load(file)

import json

text = '{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}'

dict_from_text = json.loads(text)

欲了解更多信息,请参阅https://realpython.com/python-json/

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2020-12-29
    • 2021-05-16
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多