Python中字典与字符串互转问题:写入文件后读取转成列表
问题根源分析
嘿,我知道你为啥遇到这个问题啦!核心原因是你写入文件的不是字典本身,而是字典的键值对视图(dic1.items())的字符串形式。dict.items()返回的是dict_items对象,转成字符串后看起来就是[('key', 'value'), ...]这种列表嵌套元组的结构,所以用ast.literal_eval解析后自然得到列表,而非字典。
两种解决方法
方法一:直接存储字典本身的字符串(用ast.literal_eval解析)
这种方法适合简单的字典结构,直接把字典转成字符串写入,读取时再转回字典:
import ast # 定义你的字典 dic1 = {'people': '1', 'date': '01/01/1970', 't0': 'epoch', 'time': '0', 'p0': 'Tim Berners-Lee', 'memory': 'This is the ...'} # 写入文件(用with语句自动管理文件,比手动close更安全) with open("testfile.txt", "w") as f: print(type(dic1)) # 输出 <class 'dict'> f.write(str(dic1) + "\n") # 读取并转回字典 with open("testfile.txt", "r") as f: content = f.read().strip() dic_from_file = ast.literal_eval(content) print(type(dic_from_file)) # 现在会输出 <class 'dict'> print(dic_from_file)
方法二:用json模块(更推荐,兼容性更强)
如果你的字典包含更复杂的结构(比如嵌套字典、列表等),用json模块是更稳妥的选择,因为它是标准的数据序列化格式:
import json # 定义你的字典 dic1 = {'people': '1', 'date': '01/01/1970', 't0': 'epoch', 'time': '0', 'p0': 'Tim Berners-Lee', 'memory': 'This is the ...'} # 写入文件 with open("testfile.txt", "w") as f: print(type(dic1)) json.dump(dic1, f) # 读取并转回字典 with open("testfile.txt", "r") as f: dic_from_file = json.load(f) print(type(dic_from_file)) print(dic_from_file)
补充:如果非要用
items()的补救方法 如果你已经写入了items()的内容,也可以在读取后把列表转成字典:
import ast with open("testfile.txt", "r") as f: content = f.read().strip() list_from_file = ast.literal_eval(content) dic_from_file = dict(list_from_file) # 把键值对列表转成字典 print(type(dic_from_file)) # 输出 <class 'dict'>
内容的提问来源于stack exchange,提问作者WalterTheSoyBoy
相关产品推荐
相关产品推荐

