【问题标题】:How to take the dict into .txt file, when my keys are tuple? [duplicate]当我的键是元组时,如何将 dict 放入 .txt 文件? [复制]
【发布时间】: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 被限制为strintfloatboolNone。一定要用json吗?
  • 错误很明显 JSON 的键不能是元组,因此不能使用 json.dumps 保存到文件
  • 你希望输出是什么?
  • 还有其他模块可以将dict写入文本文件吗?
  • 删除import json 行并将json.dumps 替换为str

标签: python json dictionary


【解决方案1】:

您可以在加载到 json 之前将您的元组转换为字符串:

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

def map_dict(d):
    return {str(k): v for k, v in d.items()}


with open('dict.txt', 'w') as file:
    file.write(json.dumps(map_dict(dict)))

也可以直接将dict转为str:

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}

with open('dict.txt', 'w') as file:
    file.write(str(dict))

【讨论】:

    【解决方案2】:

    您可以将键转换为字符串。

    new_dict = {}
    for k,v in dict.items():
        new_dict[str(k)] = v
    

    然后你可以将 new_dict 写入文本文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 2020-06-01
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多