简体   繁体   English

将格式化的字典元素打印到文件中

[英]Printing formatted dictionary elements into a file

I have the following dictionary:我有以下字典:

sorted_dict = {'10': ('cola', '100', '1.0USD'), '2': ('shampoo', '300', '3.125USD'), '3': ('vaseline', '180', '10USD'), '4': ('chips', '150', '15USD'), '6': ('chocolate', '0', '20USD'), '1': ('tissue', '200', '30USD'), '5': ('cup', '0', '100USD'), '7': ('candy', '11', '135USD'), '9': ('lamp', '0', '220USD'), '8': ('juice', '15220', '1002USD')}

I want to write the contents of this dictionary to a text file in the following format:我想将这本词典的内容写入以下格式的文本文件中:

10: cola, 100, 1.0USD
2: shampoo, 300, 3.125USD
...

I tried printing it using file.write(str(sorted_dict)) but it converts as follows:我尝试使用file.write(str(sorted_dict))打印它,但它转换如下:

{'10': ('cola', '100', '1.0USD'), '2': ('shampoo', '300', '3.125USD'), '3': ('vaseline', '180', '10USD'), '4': ('chips', '150', '15USD'), '6': ('chocolate', '0', '20USD'), '1': ('tissue', '200', '30USD'), '5': ('cup', '0', '100USD'), '7': ('candy', '11', '135USD'), '9': ('lamp', '0', '220USD'), '8': ('juice', '15220', '1002USD')}

How can I print out the contents of the dictionary in a way that matches the above format?怎样才能按照上面的格式打印出字典的内容呢?

You need to iterate over each key-value pair in the dictionary, and then write to the file while processing one pair at a time with a format string:您需要遍历字典中的每个键值对,然后写入文件,同时使用格式字符串一次处理一对:

with open('result.txt', 'w') as file:
    for key, value in sorted_dict.items():
        file.write(f"{key}: {', '.join(value)}\n")

Then, result.txt contains:然后, result.txt包含:

10: cola, 100, 1.0USD
2: shampoo, 300, 3.125USD
3: vaseline, 180, 10USD
4: chips, 150, 15USD
6: chocolate, 0, 20USD
1: tissue, 200, 30USD
5: cup, 0, 100USD
7: candy, 11, 135USD
9: lamp, 0, 220USD
8: juice, 15220, 1002USD
file.write(str(sorted_dict)

So, lets read this code:那么,让我们阅读这段代码:

str(sorted_dict) # Equals to
sorted_dict.__str__()

so you are just writing to your file the dict ionary, without formatting it.所以你只是把dict写入你的file ,而不是格式化它。


I would suggest something like this:我会建议这样的事情:

for key, value in sorted_dict.items():
    file.write(f"{key}: {value}\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM