将嵌套字典写入 .txt 文件

22 浏览
0 Comments

将嵌套字典写入 .txt 文件

这个问题已经有了答案

如何漂亮地打印嵌套的字典?

我有一个像这样的字典

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

然后我想要以这个格式写入到.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
      }
}

我想要去掉标点符号和括号。有一种我看不到的方法吗?

admin 更改状态以发布 2023年5月21日
0
0 Comments

如果您使用保留字典插入键顺序的Python 3.6,您可以使用类似于以下内容的代码。 \n

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')

\n通过将f.write更改为print,这个代码可以工作,我希望这可以帮助您。

0
0 Comments

你需要手动编写你的字典。你不是在尝试产生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)

print()函数会为我们处理换行符。

0