Writing a dict to a file with a certain format
-
22-12-2019 - |
Question
If I wanted to write a dict to a file with a specific format for each line what would be the best way to do this?
Currently I am doing:
with open('filename', 'w') as j:
print(dct, file = j)
But my output is, as you would expect:
{<key>: <value>, <key>: <value>, <key>: <value>}
Is there a simple way to format the output so it reads that same dict as:
<key> <value>
<key> <value>
<key> <value>
Solution
You could do it as follows:
def write_dict(out_dict, filename):
with open(filename, 'w') as f:
for key, value in out_dict.items():
f.write('{} {}\n'.format(key, value))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow