I have a dictionary
{'12345': ['paper', '3'], '67890': ['pen', '78'], '11223': ['olive', '100'], '33344': ['book', '18']}
I need to output it to textfile like this:
12345 paper 3
67890 pen 78
11223 olive 100
33344 book 18
i tried this one:
output = open("output.txt", "w")
for k, v in dict3.items():
output.writelines(f'{k} {v}\n')
Вut i got this:
12345 ['paper', '3']
67890 ['pen', '78']
11223 ['olive', '100']
33344 ['book', '18']
I have no idea how yo do it.How can I write a dictionary to a text file correctly?
CodePudding user response:
You can simply replace {v}
with {v[0]} {v[1]}
:
output = open("output.txt", "w")
for k, v in dict3.items():
output.writelines(f'{k} {v[0]} {v[1]}\n')
CodePudding user response:
If we want to write a dictionary object, we either need to convert it into string using json or serialize it. ... Write a dictionary to a file in Python
- Import Json.
- Create A Dictionary in-order pass it into text file.
- Open file in write mode.
- Use json. dumps() for json string.
For more help and to do it other way around you can approach the following link !!
https://www.geeksforgeeks.org/write-a-dictionary-to-a-file-in-python/