每天一習題,提升Python不是問題!!有更簡潔的寫法請評論告知我!
https://www.cnblogs.com/poloyy/category/1676599.html
題目
有一個數據list of dict如下 a = [ {"test1": "123456"}, {"test2": "123456"}, {"test3": "123456"}, ] 寫入到本地一個txt文件,內容格式如下: test1,123456 test2,123456 test3,123456
解題思路
- 打開文件
- 循環列表,提取字典
- 提取key,value
- 寫入文件
答案
lists = [ {"yoyo1": "111111"}, {"yoyo2": "222222"}, {"yoyo3": "333333"}, ] with open("test.txt", "w+", encoding="utf-8") as f: for data in lists: for key, value in data.items(): f.write(f"{key},{value}\n")
