Python如何将字典中列表值转为字符串后写入文本文件?
解决字典列表值转逗号分隔字符串写入文件的问题
你只需要把列表值用','.join()方法转换成逗号分隔的字符串即可,这是Python中处理字符串列表拼接的基础方法,完全符合你不用额外内置工具的要求。修改后的函数如下:
def write_dict_to_file(dictionary): with open("file.txt", 'w') as f: for key, value in dictionary.items(): # 将列表转为逗号分隔的字符串 str_value = ','.join(value) f.write('%s:%s\n' % (key, str_value))
测试示例
用你给出的示例字典测试:
test_dict = {'key1': ['string1', 'string2', 'string3'], 'key2': ['string4', 'string5', 'string6'], 'key3': ['string7', 'string8', 'string9']} write_dict_to_file(test_dict)
写入file.txt的内容会是:
key1:string1,string2,string3 key2:string4,string5,string6 key3:string7,string8,string9
注意:原函数名quit是Python内置函数名,建议改名避免命名冲突,比如改成write_dict_to_file。
内容的提问来源于stack exchange,提问作者Cr3
相关产品推荐
相关产品推荐

