将嵌套字典写入 .txt 文件

Writing a nested dictionary to a .txt file

我有一本看起来像这样的字典

{'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
      }
}

我想删除标点符号和括号。有没有办法做到这一点我看不到?

您需要手动编写字典。您不是要在此处生成 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() 函数为我们处理换行。

如果你使用 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 以供印刷。希望对您有所帮助。