我有一个.txt文件(test.txt),其中包含一个示例字典
{"1": "John", "2": "Jeremy", "3": "Jake"}
在python中,我试图从这个文本文件中获取字典,并在我的程序中使用它作为字典,但是变量的类不是字典,而是'str‘类。
dictionary = open("test.txt", mode="r")
print(dictionary)
print(type(dictionary)
Output:
{"1": "John", "2": "Jeremy", "3": "Jake"}
<class 'str'>
我只想知道如何使这个变量成为字典而不是字符串。
谢谢
发布于 2022-08-21 16:52:40
我要做一些假设。
首先,代码中的dictionary
是一个文件,而不是字符串。你忘了read
。其次,文件中的数据不是有效的字典。这些名字需要被引用。
假设它们被引用,那么您拥有的就是JSON。使用json.load
内容:
{ "1": "John", "2": "Jeremy", "3": "Jake" }
代码:
import json
dictionary = json.load(open('test.txt'))
发布于 2022-08-21 16:58:32
首先,您不能将此字符串转换为字典,因为它的格式不正确,应该如下所示
dictionary = '{"1": "John", "2": "Jeremy", "3": "Jake"}'
注意我是如何在"“之间添加名称的。
对于转换,您将使用json库。
完整法典:
import json
dictionary = open("test.txt", mode="r").read()
conv = json.loads(dictionary)
print(conv)
print(type(conv))
下面是我测试的代码:
import json
str = '{"1": "John", "2": "Jeremy", "3": "Jake"}'
conv = json.loads(str)
print(conv)
print(type(conv))
如果您不修复您的.txt文件,我的可能无法工作。
https://stackoverflow.com/questions/73439259
复制相似问题