将打开的文件中的字符串转换为字典



文本文件包含如下所示的字典

{
"A":"AB","B":"BA"
}

以下是python文件的代码

with open('devices_file') as d:
print (d["A"])

结果应打印AB

正如@rassar和@Ivrf在评论中建议的那样,您可以使用ast.literal_eval()json.loads()来实现这一点。两个代码段都输出AB

ast.literal_eval():解决方案

import ast
with open("devices_file", "r") as d:
content = d.read()
result = ast.literal_eval(content)
print(result["A"])

json.loads():解决方案

import json
with open("devices_file") as d:
content = json.load(d)
print(content["A"])

关于ast.eval_literal((和json.load((.的Python文档


另外:我注意到您在问题的代码片段中没有使用正确的语法。缩进的行应该缩进4个空格,并且在print关键字和相关的括号之间不允许有空格。

最新更新