简体   繁体   English

CSV字典-Python

[英]Dictionary to CSV - Python

I am attempting to print a dictionary to CSV and receive this error when I run the code. 我尝试将字典打印为CSV并在运行代码时收到此错误。

Error: ValueError: dict contains fields not in fieldnames: 'u', 'r', 'l' 错误:ValueError:dict包含不在字段名称中的字段:'u','r','l'

from nytimesarticle import articleAPI
import csv
api = articleAPI('API Key')

res = api.search( q = ['Abbott Laboratories'],
    fq = {'source':['The New York Times']},
    begin_date = 20110101, end_date = 20131231,
    facet_field = ['source'], facet_filter = True)

for m in res['response']['docs']:
    dic = {}
    dic['url'] = m['web_url']
    dic['id'] = m['_id']
    print dic

with open('Abbot_test.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, ('url', 'id'))
    dict_writer.writeheader()
    dict_writer.writerows(dic)

When I run with 当我与

dict_writer = csv.DictWriter(outputfile, ('url', 'id', 'u', 'r', 'l')

Error: AttributeError: 'str' object has no attribute 'get' 错误:AttributeError:'str'对象没有属性'get'

As a side note, when I run the block of code above with 附带说明一下,当我使用

dict_writer.writerow(dic)

In the last line, it prints a single url to the CSV with no error. 在最后一行中,它将没有错误地输出到CSV的单个URL。

Any thoughts? 有什么想法吗?

Looks like your dic = {} creates a blank dictionary every time in the loop. 看起来您的dic = {}每次在循环中都会创建一个空白字典。 if you're going to do that, then you have to have that loop inside of the " with open " block (so the blank dict is created, then written each time). 如果要执行此操作,则必须在“ with open ”块中包含该循环(因此将创建空白字典,然后每次编写)。 and at that point it would be " writerow " 到那时,这将是“ writerow

Well you're trying to write multiple rows, with the writerows method, but you only supply 1 row. 好吧,您正在尝试使用writerows方法编写多行,但您只提供了1行。 You need to supply a list, of dicts, that contain the proper keys. 您需要提供包含适当键的字典列表。 When Python tries to split the list into individual objects when it loops, it fails because it tries to split one object. 当Python在循环时尝试将列表拆分为单个对象时,它会失败,因为它试图拆分一个对象。 This is also why writerow (no s) works for you, because you supply only one dict. 这也是为什么writerow (no)为您工作的原因,因为您仅提供一个字典。

In short, supply a list of dictionaries, not one. 简而言之,请提供一份词典列表,而不是一份。

dict_writer.writerows([dic])

But seems like you're only creating one and rewriting it - you probably want to write it into a list instead. 但是似乎您只是创建一个并重写它-您可能想将其写入列表中。

dictlist = []
for m in res['response']['docs']:
    dic = {}
    dic['url'] = m['web_url']
    dic['id'] = m['_id']
    dictlist.append(dic)

dict_writer.writerows(dictlist)

The argument of writerows must be an iterable of dicts . 的说法writerows必须是一个迭代dicts Every row in your csv is represented by a single dict . csv中的每一行都由一个dict表示。 You keep overriding the same dict when you ought to collect them: 当您应该收集它们时,您将继续覆盖相同的dict

dics = []  # desired structure: [{..}, {..}, ...]
for m in res['response']['docs']:
    dic = {}
    dic['url'] = m['web_url']
    dic['id'] = m['_id']
    dics.append(dic)

# ....
dict_writer.writerows(dics)

Writerows iterates through whatever you pass it and, assuming iterating through dicts it calls the get method, which fails if it is actually iterating through the string keys of a single dict . Writerows遍历无论你通过它,并假设通过迭代dicts ,它调用get方法,如果它实际上是通过字符串遍历其失败keys单一的dict

its actually as easy as the following if you just wanna do it all at once: 如果您想一次完成所有操作,则实际上与以下操作一样简单:

listWriter = csv.DictWriter(
   open('FULL_PATH/output.csv', 'wb'),
   fieldnames=itemDict[itemDict.keys()[0]].keys(),
   delimiter=',',
   quotechar='|',
   quoting=csv.QUOTE_MINIMAL
)

where itemDict is your dictionary to convert. 其中itemDict是要转换的字典。

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

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