【问题标题】:How to turn a dictionary written to a .txt file, into an actual dictionary in python如何将写入.txt文件的字典转换为python中的实际字典
【发布时间】:2022-08-22 08:52:40
【问题描述】:

我有一个 .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\'>

只想知道如何使这个变量成为字典而不是字符串

谢谢

  • 如果键总是字符串,您可以使用json.load

标签: python dictionary


【解决方案1】:

我将做一些假设。

首先,您的代码中的dictionary 是一个文件,而不是一个字符串。你忘记了read。其次,您文件中的数据不是有效的字典。名称需要引用。

假设它们被引用,那么您拥有的是 JSON。使用json.load

内容:

{ 1: "John", 2: "Jeremy", 3: "Jake" }

代码:

import json
dictionary = json.load(open('test.txt'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2022-06-15
    • 2021-08-30
    • 1970-01-01
    • 2019-05-26
    • 2020-09-21
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多