I've got a dictionary with multiple rows from my question before. It's generated via:
import requests
from bs4 import BeautifulSoup
import re
import csv
links = ["34519-kevitsa-copper-concentrator-plant", "34520-kevitsa-copper-mine", "34356-glogow-copper-refinery"]
for l in links:
page = requests.get("https://www.industryabout.com/country-territories-3/2199-finland/copper-mining/"+l)
soup = BeautifulSoup(page.content, 'lxml')
rows = soup.select("strong")
d = {}
for r in rows:
name, value, *rest = r.text.split(":")
if not rest:
d[name] = value
print(d)
print(d.items())
gives:
dict_items([('Commodities', ' Copper, Nickel, Gold'), ('Area', ' Lappi'), ('Type', ' Copper Concentrator Plant') ])
dict_items([('Commodities', ' Copper, Nickel, Gold'), ('Area', ' Lappi'), ('Type', ' Open-pit Mine') ])
dict_items([('Commodities', ' Copper'), ('Area', ' Dolnoslaskie'), ('Type', ' Copper Refinery') ])
But when I write this to CSV with any of the solutions from "Writing a dictionary to a csv file with one line for every 'key: value'" I only get the LAST dictionary item, the others are omitted.
Commodities;Copper
Area;Dolnoslaskie
Type;Copper Refinery
How can I write a CSV with looks like this:
Commodities;Area;Type
Copper, Nickel, Gold;Lappi;Copper Concentrator Plant
Copper, Nickel, Gold;Lappi;Open-pit mine
Copper;Dolnoslaskie;Copper Refinery
I've also tried to change to an array, but coulnd't find a solution for array[name] = value
.
This answer seems perfect, but iterkeys is Python 2 only.
with open('my_data.csv', 'wb') as ofile:
writer = csv.writer(ofile, delimiter='\t')
writer.writerow(['ID', 'dict1', 'dict2', 'dict3'])
for key in ddict.iterkeys():
writer.writerow([key] + [d[key] for d in dicts])