【发布时间】:2021-12-19 07:58:44
【问题描述】:
当我的密钥是tuple 时,如何将dict 转换为.txt file?
当我的密钥为int时,它可以成功运行。
但是当密钥为tuple时,它会失败。
dict = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (4, 4): 44, (5, 5): 55, (6, 6): 66, (7, 7): 77, (8, 8): 88, (9, 9): 99}
import json
with open('dict.txt', 'w') as file:
file.write(json.dumps(dict))
TypeError: keys must be str, int, float, bool or None, not tuple
【问题讨论】:
-
你不能。正如错误所说,json-keys 被限制为
str、int、float、bool或None。一定要用json吗? -
错误很明显 JSON 的键不能是元组,因此不能使用 json.dumps 保存到文件
-
你希望输出是什么?
-
还有其他模块可以将dict写入文本文件吗?
-
删除
import json行并将json.dumps替换为str
标签: python json dictionary