【问题标题】:Appending a python dictionary to csv将 python 字典附加到 csv
【发布时间】:2012-09-26 00:58:59
【问题描述】:

我正在尝试将一些 API JSON 数据导出到 csv,但我只想要其中的一部分。我试过row.append,但我收到错误TypeError: string indices must be integers。

我是 python 新手,有点困惑为什么它需要一个整数。

import urllib2
import json
import csv

outfile_path='/NYTComments.csv'

writer = csv.writer(open(outfile_path, 'w'))

url = urllib2.Request('http://api.nytimes.com/svc/community/v2/comments/recent?api-key=ea7aac6c5d0723d7f1e06c8035d27305:5:66594855')

parsed_json = json.load(urllib2.urlopen(url))

print parsed_json

for comment in parsed_json['results']:
    row = []
    row.append(str(comment['commentSequence'].encode('utf-8')))
    row.append(str(comment['commentBody'].encode('utf-8')))
    row.append(str(comment['commentTitle'].encode('utf-8')))
    row.append(str(comment['approveDate'].encode('utf-8')))
    writer.writerow(row)

parsed_json 打印出来的样子是这样的:

{u'status': u'OK',
u'results':
    {u'totalCommentsReturned': 25,
    u'comments':
        [{
            u'status': u'approved',
            u'sharing': 0,
            u'approveDate': u'1349378866',
            u'display_name': u'Seymour B Moore',
            u'userTitle': None,
            u'userURL': None,
            u'replies': [],
            u'parentID': None,
            u'articleURL': u'http://fifthdown.blogs.nytimes.com/2012/10/03/thursday-matchup-cardinals-vs-rams/',
            u'location': u'SoCal',
            u'userComments': u'api.nytimes.com/svc/community/v2/comments/user/id/26434659.xml',
            u'commentSequence': 2,
            u'editorsSelection': 0,
            u'times_people': 1,
            u'email_status': u'0',
            u'commentBody': u"I know most people won't think this is a must watch game, but it will go a long way .... (truncated)",
            u'recommendationCount': 0,
            u'commentTitle': u'n/a'
        }]
    }
}

【问题讨论】:

  • comment 是字典吗?听起来它可能是一个字符串。
  • 字典已解析_json
  • 是的,但是您似乎将评论视为字典,如果它不是字典,那么您就有问题了。

标签: python json csv dictionary


【解决方案1】:

看起来你犯了一个我一直犯的错误。而不是

for comment in parsed_json['results']:

你想要的

for comment_name, comment in parsed_json['results'].iteritems():

(或.items(),如果您使用的是 Python 3)。

只需遍历字典(大概是parsed_json['results'])就可以得到字典的键,而不是元素。如果你这样做了

for thing in {'a': 1, 'b': 2}:

然后thing 将遍历“a”和“b”。

然后,由于该键显然是一个字符串,您正在尝试执行类似"some_name"['commentSequence'] 的操作,这会导致您看到的错误消息。

另一方面,dict.iteritems() 给你一个迭代器,它会给你像('a', 1) 和('b', 2) 这样的元素; for 循环中的两个变量然后被分配给那里的两个元素,所以这里是 comment_name == 'a' 和 comment == 1。

由于您似乎实际上并没有使用来自parsed_json['results'] 的密钥,因此您也可以循环使用for comment in parsed_json['results'].itervalues()。

【讨论】:

  • 你说得对,我想要的是元素而不是键。当我改变它时,我得到:TypeError:'int' object is not subscriptable
【解决方案2】:
for comment in parsed_json['results']: #'comment' contains keys, not values

应该是

for comment in parsed_json['results']['comments']:

parsed_json['results'] 本身就是另一个字典。

parsed_json['results']['comments'] 是您要迭代的字典列表。

【讨论】:

  • 这也会产生这个错误:row.append(str(comment['commentSequence'].encode('utf-8'))) TypeError: 'int' object is not subscriptable
  • 您能否将print parsed_json 的输出添加到您的问题中,即使是样本而不是完整输出?
  • 谢谢。我已经做了。您可以在上面看到一条评论的示例。
  • 感谢您添加输出,虽然我已经能够通过使用您的代码和其中的 url 来计算它:) 现在应该可以工作了!
  • 我相信我做到了。首先,我试图检索键,而不是我想要的元素。然后,我没有意识到 JSON 有两个级别,结果然后是 cmets。非常感谢!
猜你喜欢
  • 2013-11-14
  • 2014-04-16
  • 2016-12-30
  • 2015-08-22
  • 2020-10-14
  • 1970-01-01
  • 2023-02-24
  • 2023-02-02
  • 2021-12-21
相关资源
最近更新 更多