如何使用Python将字典导出为CSV?

时间:2017-08-15 09:44:03

标签: python dictionary export-to-csv

我在将字典中的某些项目导出为CSV时遇到问题。我可以导出' name'但不是'图像' (图片网址)。

这是我字典的一部分示例:

(u32, Stream<Item=Bytes))
编辑(我的命名是错误的,正如所指出的那样。在更新之后它似乎现在正常工作)。

这是我编写的代码(适用于&#39;名称&#39;但不是&#39;图片&#39;):

new = [{ "name" : "peter", "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12"},
{"name" : "jim" , "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8"}]

2 个答案:

答案 0 :(得分:1)

Pandas更适合您的问题。

import pandas as pd

df = pf.DataFrame(list_of_dict)

df.columns = ["name", "image or picture"]

df.to_csv("test.csv", index=0)

答案 1 :(得分:1)

您的var result = fullQuery. .AsEnumerable() // db query ends here .Select(fooBar => { fooBar.Foo.Bar = fooBar.Bar; return fooBar.Foo; }) .ToList(); 列表包含包含密钥new的字典,但您尝试访问名为picture的字典。

images

您也可以使用import csv new = [ { "name" : "peter", "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12"}, {"name" : "jim" , "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8"}] test = [] for document in new: event_obj = {} # Get name event_obj['name'] = document['name'] # Get images event_obj['images'] = document['picture'] test.append(event_obj) # Create CSV file with open('Eventbrite_events.csv', 'w', newline='') as csvfile: fields = ['name', 'images'] writer = csv.DictWriter(csvfile, fieldnames=fields) writer.writeheader() writer.writerows(test) 一次性写入所有行。

这会给你一个CSV文件,如下所示:

writerows()

您还可以避免按以下方式构建name,images peter,https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12 jim,https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8 作为重命名条目的替代方法:

test