将字典转换为字符串,然后再次返回字典

Converting a dictionary to string, then back to dictionary again

在我下面的代码中,我从 yfinance 获取了一些数据,然后将其放在一个文本文件中。为了将它放在文本文件中,我需要将它从字典转换为字符串。当我想读入那个文件时,它是一个字符串,但是如果我正确理解了错误消息,我需要它是一个字典。如果有人知道如何解决这个问题,我将不胜感激。

import finance as yf

x=yf.Ticker("AAPL")
xo=x.info
f = open("atest.txt", "w")
f.write(str(xo))
f.close()
f = open("atest.txt", "r")
info=(f.read())
f.close()
print(info['forwardPE'])

错误信息:

Traceback (most recent call last):
  File "/Users/xox/Desktop/Learning/TextFile/U5.py", line 41, in <module>
    print(info['forwardPE'])
TypeError: string indices must be integers

您可以使用 json.dump 和 json.loads 来达到这个目的。在保存之前,您可以使用 json.dump 将任何对象转换为字符串。加载时,可以使用json.loads.

下面是伪代码

import json
str = json.dump(obj)
...
obj = json.loads(str)
...

如果我理解你的问题,你应该看看 json 库,从文件加载 Json 的示例代码

import json
with open('file.txt', 'r') as f:
    data = json.loads(f.read())

然后将其写入文件:

import json
data = {"1": "ABC", "2": "DEF"}
with open('file.txt', 'w') as f:
    f.write(json.dumps(data))

我认为做en/decode对象to/from字符串最常见的方法是使用JSON。 python 中有一个标准的 json 模块。您所要做的只是导入 json 并调用 json.dump 和 json.loads