将嵌套字典写入.txt fi

2024-04-20 09:57:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本像这样的字典

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

然后我想写一个.txt格式的文件

^{pr2}$

我试着用

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

我想去掉标点和括号。有没有我看不到的方法?在


Tags: 文件txt字典格式openusersmelondon
2条回答

你需要手工写字典。您并不是要在这里生成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()函数为我们处理新行。在

如果您使用python3.6,它在dictionary上保持插入键的顺序,那么可以使用类似这样的代码。在

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 for print。我希望这有帮助。在

相关问题 更多 >