如何使用python将字典列表写入excel文件?

时间:2017-08-23 06:01:46

标签: python excel pandas dataframe

我有在运行时创建数组的脚本,如下所示

[{'Currency': 'Euro', 'Age of Bike': 12, 'Build Month': '08', 'Metric': '16694 km', 'Build Year': '2005', 'Website Link': u'https://www.autoscout24.nl/aanbod/motorhispania-benzine-geel-2c73a018-35a0-4e00-a1ed-1a3375ef4c4d', 'Country': 'Nederland', 'Brand': 'Motorhispania', 'Model': '', 'Price': '650'},
 {'Currency': 'Euro', 'Age of Bike': 20, 'Build Month': '12', 'Metric': '75000 km', 'Build Year': '1996', 'Website Link': u'https://www.autoscout24.nl/aanbod/honda-cbr-1000-benzine-wit-d517ce56-0a7a-f055-e053-e350040a4a20', 'Country': 'Nederland', 'Brand': 'Honda', 'Model': 'CBR 1000', 'Price': '750'},
 {'Currency': 'Euro', 'Age of Bike': 30, 'Build Month': '03', 'Metric': '63000 km', 'Build Year': '1987', 'Website Link': u'https://www.autoscout24.nl/aanbod/kawasaki-gpz-600-benzine-wit-80a2a256-c539-9d11-e053-e350040a17e5', 'Country': 'Nederland', 'Brand': 'Kawasaki', 'Model': 'GPZ 600', 'Price': '850'},
 {'Currency': 'Euro', 'Age of Bike': 27, 'Build Month': '03', 'Metric': '61000 km', 'Build Year': '1990', 'Website Link': u'https://www.autoscout24.nl/aanbod/yamaha-xv-535-virago-virago-535-benzine-blauw-d6ee5657-3149-6b52-e053-e350040abf9d', 'Country': 'Nederland', 'Brand': 'Yamaha', 'Model': 'XV 535 Virago', 'Price': '1500'},
 {'Currency': 'Euro', 'Age of Bike': 17, 'Build Month': '06', 'Metric': '51121 km', 'Build Year': '2000', 'Website Link': u'https://www.autoscout24.nl/aanbod/yamaha-fzs-600-fazer-benzine-zilver-c2dfe981-88da-4798-85d8-13f7e61fd7fc', 'Country': 'Nederland', 'Brand': 'Yamaha', 'Model': 'FZS 600', 'Price': '1595'},
 {'Currency': 'Euro', 'Age of Bike': 8, 'Build Month': '07', 'Metric': '145771 km', 'Build Year': '2009', 'Website Link': u'https://www.autoscout24.nl/aanbod/bmw-r-1200-rt-benzine-grijs-3cab4057-2232-cc59-e053-e350040ae7fe', 'Country': 'Nederland', 'Brand': 'BMW', 'Model': 'R 1200 RT', 'Price': '4000'}]

我希望这个像这样写在excel文件中

Currency    |    Age of Bike    |    Build Month    |    Metric
Euro        |      12           |       08          |     16694 km
Euro        |      20           |       12          |     75000 km
Euro        |      30           |       03          |     63000 km

所以使用python库如pandas和xlswriter等......

1 个答案:

答案 0 :(得分:3)

data = ... # your data

df = pd.DataFrame.from_dict(data)
df = df[['Currency', 'Age of Bike', 'Build Month', 'Metric']]

print(df)

  Currency  Age of Bike Build Month     Metric
0     Euro           12          08   16694 km
1     Euro           20          12   75000 km
2     Euro           30          03   63000 km
3     Euro           27          03   61000 km
4     Euro           17          06   51121 km
5     Euro            8          07  145771 km

现在,请致电df.to_excel

df.to_excel('data.xlsx')

或者,如果您有多个数据帧要保存到多个工作表:

writer = pd.ExcelWriter('data.xlsx')
df.to_excel(writer, 'Sheet1')
... # more writes to the file 
writer.save()