如何將這些字典的鍵作為列保存,將值作為行保存到 CSV?
{'Full Name': None, 'Nick Name': None, 'profession': 'Model,
Actress', 'Height': 'in centimeters- 165 cm, in meters- 1.65 m,
in feet & inches- 5’ 5”', 'Weight': None}
{'Full Name': None, 'Nick Name': 'Chikoo, Run Machine',
'profession': 'Indian Cricketer (Batsman)', 'Height': 'in
centimeters- 175 cm, in meters- 1.75 m, in Feet Inches- 5’ 9”',
'Weight': None}
{'Full Name': 'Amitabh Harivansh Rai Shrivastava', 'Nick Name':
'Munna, Big B, Angry Young Man, AB Sr., Amith, Shahenshah of
Bollywood', 'profession': 'Actor, TV Host, Former Politician',
'Height': 'in centimeters- 188 cm, in meters- 1.88 m, in Feet
Inches- 6’ 2” [2]@SrBachchan', 'Weight': None}
uj5u.com熱心網友回復:
我看到您正在遍歷一組 URL,為每個 URL 下載 HTML,抓取該 HTML 并制作成一個 dict。
你可以只收集每個字典,然后得到類似的東西all_dicts
,正如我所展示的:
import csv
all_dicts = []
# for url in urllist:
# request url
# scrape html from url
# somehow you convert scraped html to a dict, let's call it new_dict
# all_dicts.append(new_dict)
# And, now you have all the dictionaries, and it looks something like this:
all_dicts = [
{'Full Name': None, 'Nick Name': None, 'profession': 'Model, Actress',
'Height': 'in centimeters- 165 cm, in meters- 1.65 m, in feet & inches- 5’ 5”', 'Weight': None},
{'Full Name': None, 'Nick Name': 'Chikoo, Run Machine',
'profession': 'Indian Cricketer (Batsman)', 'Height': 'in centimeters- 175 cm, in meters- 1.75 m, in Feet Inches- 5’ 9”', 'Weight': None},
{'Full Name': 'Amitabh Harivansh Rai Shrivastava', 'Nick Name': 'Munna, Big B, Angry Young Man, AB Sr., Amith, Shahenshah of Bollywood',
'profession': 'Actor, TV Host, Former Politician', 'Height': 'in centimeters- 188 cm, in meters- 1.88 m, in Feet Inches- 6’ 2” [2]@SrBachchan', 'Weight': None},
# ... more of your dicts
]
# And then you move on to writing all_dicts
with open('my.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=all_dicts[0].keys())
writer.writeheader()
writer.writerows(all_dicts)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/401940.html
上一篇:Python從csv檔案插值