代码之家  ›  专栏  ›  技术社区  ›  CEamonn

将嵌套字典写入。txt文件[重复]

  •  0
  • CEamonn  · 技术社区  · 7 年前

    我有一本这样的字典

    {'Berlin': {'Type1': 96},
     'Frankfurt': {'Type1': 48},
     'London': {'Type1': 288, 'Type2': 64, 'Type3': 426},
     'Paris': {'Type1': 48, 'Type2': 96}}
    

    然后我想写信给a。格式的txt文件

    London
      Type1: 288
      Type2: 64
      Type3: 426
    
    Paris
      Type1: 48
      Type2: 96
    
    Frankfurt
      Type1: 48
    
    Berlin
      Type1: 98
    

    我试着用

    f = open("C:\\Users\\me\\Desktop\\capacity_report.txt", "w+")
    f.write(json.dumps(mydict, indent=4, sort_keys=True))
    

    但这张照片是这样的:

    {
        "London": {
            "Type1": 288,
            "Type2": 64,
            "Type3": 426
         },
         "Paris": {
             "Type1": 48,
             "Type2": 96
         },
         "Frankfurt": {
             "Type1": 48
          },
          "Berlin": {
             "Type1": 98
          }
    }
    

    我想去掉标点符号和括号。有什么方法我看不见吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Martijn Pieters    7 年前

    你需要手动写出字典。您并没有试图在这里生成JSON,使用该模块也没有任何意义。

    迭代字典键和值,并将它们写成行。这个 print() 函数在此处可能很有用:

    from __future__ import print_function
    
    with open("C:\\Users\\me\\Desktop\\capacity_report.txt", "w") as f:
        for key, nested in sorted(mydict.items()):
            print(key, file=f)
            for subkey, value in sorted(nested.items()):
                print('   {}: {}'.format(subkey, value), file=f)
            print(file=f)
    

    这个 打印() 函数为我们处理换行符。

        2
  •  0
  •   Tzomas    7 年前

    如果您使用python 3.6,它在字典上的插入键上保持顺序,那么您可以使用类似的东西。

    with open('filename.txt','w') as f:
        for city, values in my_dict.items():
            f.write(city + '\n')
            f.write("\n".join(["  {}: {}".format(value_key, digit) for value_key, digit in values.items()]) + '\n')
            f.write('\n')
    

    它的作品改变了f.write的印刷风格。我希望这有帮助。