如何在Python中将字典列表保存至Excel或CSV文件?
将字典列表保存到CSV或Excel的Python实现
一、保存为CSV文件
你的字典中部分字段是列表类型,直接写入CSV会导致格式混乱,需要先把列表转成逗号分隔的字符串,再用Python内置的csv模块完成保存:
import csv # 原始数据 data = [ {'Area of expertise': ['Acne', 'Skin cancer', 'Moles'], 'Health insurance': ["I'm paying for myself", 'Alliance Health Group', 'Allianz', 'AVIVA'], 'Language spoken': ['English', 'Hindi'], 'Name': 'Nikhil', 'Ratings': '5', 'Types of offering': ['Call']}, {'Area of expertise': ['Acne', 'Skin cancer', 'Moles', 'Lichen sclerosus', 'Psoriasis'], 'Health insurance': ["I'm paying for myself"], 'Language spoken': ['English'], 'Name': 'Akhil', 'Ratings': '5', 'Types of offering': ['Call']} ] # 处理列表字段,转成字符串 processed_data = [] for item in data: processed_item = {} for key, value in item.items(): processed_item[key] = ', '.join(value) if isinstance(value, list) else value processed_data.append(processed_item) # 获取表头并写入CSV headers = processed_data[0].keys() with open('doctors_data.csv', 'w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() writer.writerows(processed_data)
二、保存为Excel文件
用pandas库操作更简洁(需先安装依赖:pip install pandas openpyxl),同样先处理列表字段再写入:
import pandas as pd # 原始数据 data = [ {'Area of expertise': ['Acne', 'Skin cancer', 'Moles'], 'Health insurance': ["I'm paying for myself", 'Alliance Health Group', 'Allianz', 'AVIVA'], 'Language spoken': ['English', 'Hindi'], 'Name': 'Nikhil', 'Ratings': '5', 'Types of offering': ['Call']}, {'Area of expertise': ['Acne', 'Skin cancer', 'Moles', 'Lichen sclerosus', 'Psoriasis'], 'Health insurance': ["I'm paying for myself"], 'Language spoken': ['English'], 'Name': 'Akhil', 'Ratings': '5', 'Types of offering': ['Call']} ] # 处理列表字段 for item in data: for key, value in item.items(): if isinstance(value, list): item[key] = ', '.join(value) # 转成DataFrame并写入Excel df = pd.DataFrame(data) df.to_excel('doctors_data.xlsx', index=False, engine='openpyxl')
注意事项
- 如果字典列表里存在键不一致的情况,
csv.DictWriter和pandas都会自动补空值,不用担心数据缺失。 - 用
utf-8编码能避免中文或特殊字符乱码问题。
内容的提问来源于stack exchange,提问作者Nikhil V
相关产品推荐
相关产品推荐

