简体   繁体   中英

Write to dictionary of lists to a CSV file

I want multiple values to be associated while it displays vertically. When I write the value key of my dictionary to writerows (w.writerows(d.values()) it goes horizontally, while I want it vertically.

from bs4 import BeautifulSoup
import csv
r = requests.get('https://www.ufc.com/rankings')
s = BeautifulSoup(r.text, 'lxml')
fighters = s.find_all('div','view-grouping')
name = []
weightdivisions = []
for x in fighters:
    z = [names.string for names in x.find_all('a')]
    name.append(z)
    divisions = x.find('h4')
    dd = divisions.text
    weightdivisions.append(dd)

d = dict(zip(weightdivisions,name))
print(d)
with open('ufc.csv', 'w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(d.keys())
    w.writerows(d.values())

Try:

import csv
from bs4 import BeautifulSoup


r = requests.get("https://www.ufc.com/rankings")
s = BeautifulSoup(r.text, "lxml")
fighters = s.find_all("div", "view-grouping")
name = []
weightdivisions = []
for x in fighters:
    z = [names.string for names in x.find_all("a")]
    name.append(z)
    divisions = x.find("h4")
    dd = divisions.text
    weightdivisions.append(dd)

d = dict(zip(weightdivisions, name))
with open("ufc.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(d.keys())

    for column in d:
        d[column] = iter(d[column])

    while True:
        row = [next(d[column], "") for column in d]
        if all(val == "" for val in row):
            break
        w.writerow(row)

This saves ufc.csv correctly (screenshot from LibreOffice):

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM