简体   繁体   English

Python:将具有多行的字典写入CSV

[英]Python: Write dictionary with multiple rows to CSV

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: print(d.items())给出:

dict_items([('Commodities', ' Copper, Nickel, Gold'), ('Area', ' Lappi'), ('Type', ' Copper Concentrator Plant') ]) dict_items([('商品','铜,镍,金'),('区域','拉皮'),('类型','铜选矿厂']])

dict_items([('Commodities', ' Copper, Nickel, Gold'), ('Area', ' Lappi'), ('Type', ' Open-pit Mine') ]) dict_items([('商品','铜,镍,金'),('区域','拉皮'),('类型','露天矿']])

dict_items([('Commodities', ' Copper'), ('Area', ' Dolnoslaskie'), ('Type', ' Copper Refinery') ]) 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. 但是,当我使用以下解决方案中的任何一种将其写入CSV时:“ 将字典写到csv文件中,每个'key:value'一行, ”仅得到LAST字典项,其余的省略。

Commodities;Copper
Area;Dolnoslaskie
Type;Copper Refinery

How can I write a CSV with looks like this: 如何编写具有以下内容的CSV文件:

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 . 我也尝试过更改为数组,但是找不到array[name] = value的解决方案。

This answer seems perfect, but iterkeys is Python 2 only. 这个答案似乎很完美,但是iterkeys仅适用于Python 2。

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])
import csv

with open('data.csv', 'w') as outfile:
    writer = csv.DictWriter(outfile, ['Commodities', 'Area', 'Type'], delimiter=';')
    writer.writeheader()
    for l in links:
        ...
        print(d)
        writer.writerow(d)

You can try this. 你可以试试看

#!python
# -*- coding: utf-8 -*-#

d = {k:v for (k,v) in zip(list('abc'),range(3))}
print(d)

with open('a.txt','w') as fo:
    for i in d:
        line = '{};{}\n'.format(i,d[i])
        fo.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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