所以基本上,我有一个api,其中有几个字典/数组。(http://dev.c0l.in:5984/income_statements/_all_docs) 当从api获取每个公司的财务信息时(例如,sector=technology and statement=income),python应该返回614家技术公司,但是我得到以下错误:
Traceback (most recent call last):
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 83, in <module>
user_input1()
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 75, in user_input1
income_statement_fn()
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 51, in income_statement_fn
if is_response ['sector'] == user_input3:
KeyError: 'sector'
在一个随机的公司(通常在第550-600个公司之一)
这是损益表的函数
def income_statement_fn():
user_input3 = raw_input("Which sector would you like to iterate through in Income Statement?: ")
print 'Starting...'
for item in income_response['rows']:
is_url = "http://dev.c0l.in:5984/income_statements/" + item['id']
is_request = urllib2.urlopen(is_url).read()
is_response = json.loads(is_request)
if is_response ['sector'] == user_input3:
csv.writerow([
is_response['company']['name'],
is_response['company']['sales'],
is_response['company']['opening_stock'],
is_response['company']['purchases'],
is_response['company']['closing_stock'],
is_response['company']['expenses'],
is_response['company']['interest_payable'],
is_response['company']['interest_receivable']])
print 'loading...'
print 'done!'
print end - start
知道是什么导致了这个错误吗? (我不相信这是api本身)
干杯
问题似乎出在
income_response
数据的最后一行它没有
sector
值。您需要修改代码来处理这一行,例如忽略任何没有sector
键的行。你知道吗您可以使用一些print语句(例如insert)轻松地对此进行调试
在输出CSV的部分之前输入代码。你知道吗
好吧,在测试
urlopen
调用中传递的url时,使用一个随机数,我得到如下结果:在这种情况下,您的函数将准确返回您得到的错误。如果您希望您的程序能够很好地处理错误,并添加一个“缺少的”行而不是实际数据,您可以这样做,例如:
KeyError
表示您试图使用的键在字典中不存在。在检查密钥时,使用.get()
更安全。所以你要替换这行:有了这个:
相关问题 更多 >
编程相关推荐