[英]How to turn a dictionary written to a .txt file, into an actual dictionary in python
I have a.txt file (test.txt) with an example dictionary written in it我有一个.txt 文件(test.txt),里面有一个示例字典
{"1": "John", "2": "Jeremy", "3": "Jake"}
In python I'm trying to grab the dictionary from this text file, and use it as a dictionary in my program, but the class of the variable isn't a dictionary, it's the 'str' class.在 python 我试图从这个文本文件中获取字典,并将其用作我的程序中的字典,但变量的 class 不是字典,它是“str” ZA2F2ED4F8EBC2CBB4C21A29DC40AB16
dictionary = open("test.txt", mode="r")
print(dictionary)
print(type(dictionary)
Output:
{"1": "John", "2": "Jeremy", "3": "Jake"}
<class 'str'>
Just want to know how I can make this variable a dictionary instead of a string只想知道如何使这个变量成为字典而不是字符串
Thanks谢谢
I'm going to make a number of assumptions.我将做一些假设。
First, dictionary
in your code is a file, not a string.首先,代码中的dictionary
是文件,而不是字符串。 You forgot the read
.你忘了read
。 Second, the data in your file is NOT a valid dictionary.其次,您文件中的数据不是有效的字典。 The names need to be quoted.名称需要引用。
Assuming they are quoted, what you have is JSON.假设它们被引用,你所拥有的是 JSON。 Use json.load
:使用json.load
:
Contents:内容:
{ "1": "John", "2": "Jeremy", "3": "Jake" }
Code:代码:
import json
dictionary = json.load(open('test.txt'))
First of all you can't convert this string to a dictionary as its format isn't correct, it should be like this首先,您不能将此字符串转换为字典,因为它的格式不正确,应该是这样的
dictionary = '{"1": "John", "2": "Jeremy", "3": "Jake"}'
notice how I added the names between the ""请注意我是如何在“”之间添加名称的
For the conversion you will use json library对于转换,您将使用 json 库
Full Code:完整代码:
import json
dictionary = open("test.txt", mode="r").read()
conv = json.loads(dictionary)
print(conv)
print(type(conv))
This is the code I tested with:这是我测试的代码:
import json
str = '{"1": "John", "2": "Jeremy", "3": "Jake"}'
conv = json.loads(str)
print(conv)
print(type(conv))
My might not work if you don't fix your.txt file.如果您不修复您的 .txt 文件,我可能无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.