如何编写以字典键作为列名、以字典值作为列值的excel文件?

2024-10-04 09:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典如下:

[{'tarih': '01.02.2019', '4980': 1.1517482514, '2738': 0.9999999999999999, '0208': 1.0102518747365854},{'tarih': '02.02.2019', '4980': 1.1517486767, '2738': 0.9999999999999999, '0208': 1.0102518747368554}]

我想写一个excel文件,如:

tarih          4980           2738                   0208               // dictionary keys as column name
01.02.2019     1.1517482514   0.9999999999999999     1.0102518747365854 // dict values as value
02.02.2019     1.1517486767   0.9999999999999999     1.0102518747368554 // dict values as value

Tags: 文件namedictionary字典valueascolumnkeys
2条回答
import csv
with open('dict.csv', 'w', newline="") as csv_file:  
    writer = csv.writer(csv_file)
    for key, value in mydict.items():
       writer.writerow([key, value])

您可以使用pandas模块完成此操作

import pandas as pd

x = [{'tarih': '01.02.2019', '4980': 1.1517482514, '2738': 0.9999999999999999, '0208': 1.0102518747365854},{'tarih': '02.02.2019', '4980': 1.1517486767, '2738': 0.9999999999999999, '0208': 1.0102518747368554}]

df = pd.DataFrame(x)

df.to_excel ('test.xlsx', sheet_name = 'sheet1', index = False)

输出:

     tarih      4980        2738    0208
0   01.02.2019  1.151748    1.0    1.010252
1   02.02.2019  1.151749    1.0    1.010252

相关问题 更多 >