【问题标题】:How can I save all dictionary to a CSV file?如何将所有字典保存到 CSV 文件?
【发布时间】:2022-01-01 10:45:56
【问题描述】:

如何将这些字典的键作为列保存,将值作为行保存到 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}
   
    

【问题讨论】:

  • 到底是什么问题?你有什么错误吗?另外,请不要张贴图片,请将 dict 的文本复制到此帖子中。谢谢,欢迎! :)
  • 我想说你如何生成字典是无关紧要的。你有许多字典,你想把它们变成一个 CSV。我相信我的回答向您展示了如何做到这一点。不过,在请求和抓取方面做得很好! :)

标签: python python-3.x csv


【解决方案1】:

我看到您正在遍历一组 URL,下载每个 URL 的 HTML,抓取该 HTML 并制作成一个字典。

您可以只收集每个字典,然后得到类似 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)

【讨论】:

  • 嘿@Zach Young,感谢您的快速回复。我刚刚更新了我的问题的详细信息。
  • 它不工作!
  • 我的代码或设置有什么问题?我的答案中的 my.csv 看起来是否正确?我完全复制了您的print(newdicts) 的输出(除了必须在每个字典之间添加逗号,并且必须修复所有换行符)。
  • 你的做法是正确的。但问题是您将所有字典添加到列表中。如果您检查了我的整个代码,那对我来说是不可能的。我正在寻找 2 个解决方案。有什么方法可以在不添加列表的情况下将所有字典写入 CSV?或者我怎样才能把我所有的字典都放在列表中?
  • 我已经阅读了你的代码,但我不明白你不可能做什么。我看到您有能力对您的代码进行一些小的更改,并在创建每个 dict 时收集它,然后一次编写它们。你还没有说为什么你不能这样做。我已经更新了我的帖子以尝试反映您的代码的想法。
猜你喜欢
  • 2021-09-28
  • 2021-07-04
  • 2021-08-26
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 2021-05-08
相关资源
最近更新 更多