我写了一个小函数来用Python提取字典并将其转换为txt文件。
def dict_to_txt(dict, name):
dict = {'dict': dict}
with open('{}.txt'.format(name), 'w') as file:
file.write(json.dumps(dict))
我的输出如下:
{"dict": {"A": "America", "B": NaN, "C": "?", "D": NaN}}
有什么办法可以输出这样的格式化字典:
{"dict": {"A": "America",
"B": NaN,
"C": "?",
"D": NaN
}
}
或某些变化。为了给您一些背景信息,我有一个包含字典的列表,并且正在通过遍历列表来应用此功能。
答案 0 :(得分:2)
def dict_to_txt(dict, name):
dict = {'dict': dict}
with open('{}.txt'.format(name), 'w') as file:
file.write(json.dumps(dict), indent=2)