怎么让嵌套再列表中的字典转换成Excel表格
时间: 2023-05-27 17:06:08 浏览: 136
可以使用Python中的pandas库将嵌套在列表中的字典转换成Excel表格。
首先,将列表中的字典转换成pandas的DataFrame对象,然后使用to_excel()方法将DataFrame对象保存为Excel文件。
以下是一个示例代码:
```python
import pandas as pd
data = [{'name': 'Alice', 'age': 25, 'scores': {'math': 90, 'english': 85}},
{'name': 'Bob', 'age': 30, 'scores': {'math': 80, 'english': 75}},
{'name': 'Charlie', 'age': 35, 'scores': {'math': 95, 'english': 90}}]
df = pd.DataFrame(data)
df.to_excel('scores.xlsx', index=False)
```
在这个示例中,我们有一个包含三个字典的列表,每个字典包含姓名、年龄和成绩等键值对。成绩是另一个嵌套的字典。
我们使用pandas的DataFrame()函数将列表转换成DataFrame对象,然后使用to_excel()方法将DataFrame对象保存为Excel文件。设置index=False参数可以避免将DataFrame的索引保存到Excel文件中。
结果是一个名为“scores.xlsx”的Excel文件,其中包含一个名为“Sheet1”的工作表,其中包含我们的数据。