You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本文件中的字符串转换为字典并正确实现字典备份

How to Convert a Dictionary String from a Text File to a Python Dictionary

Hey Marcus, I get exactly what you're dealing with here—right now you're pulling the file content as a plain string, but you need it to be a proper Python dictionary you can work with. Lucky for you, since your text file has valid JSON syntax (which matches up almost perfectly with Python dict structure), we can fix this easily with Python's built-in json module.

Here's the straightforward fix for your code:

import json

with open("dict.txt", "r") as dict_file:
    my_dict = json.load(dict_file)

This code skips reading the raw string entirely—json.load() takes the open file object directly and parses its content straight into a dictionary. You’ll be able to access values like my_dict["test"] or my_dict["dict"][0] just like you would with any regular Python dict.

If you need to read the string first (maybe for some quick edits or validation before parsing), you can use json.loads() instead:

import json

with open("dict.txt", "r") as dict_file:
    text = dict_file.read()
    my_dict = json.loads(text)

A quick reminder to keep your file content valid JSON: JSON requires double quotes (which you already have in your example) instead of single quotes, so as long as you stick to that when writing back to the file later, everything will work smoothly. When you need to save your dictionary back to the file, use json.dump(my_dict, open("dict.txt", "w")) to maintain the correct format.

内容的提问来源于stack exchange,提问作者Marcus Weinberger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:50:44