簡體   English   中英

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

[英]Printing formatted dictionary elements into a file

我有以下字典:

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

我想將這本詞典的內容寫入以下格式的文本文件中:

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

我嘗試使用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')}

怎樣才能按照上面的格式打印出字典的內容呢?

您需要遍歷字典中的每個鍵值對,然后寫入文件,同時使用格式字符串一次處理一對:

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

然后, 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)

那么,讓我們閱讀這段代碼:

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

所以你只是把dict寫入你的file ,而不是格式化它。


我會建議這樣的事情:

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