python读取csv时keyerror_Python:默认字典键,以避免KeyError

Fairly new to python, novice developer, first time caller

I'm calling some JSON and parsing relevant data as csv. I cannot figure out how to fill in the intermediate json Dict file with default keys, as many are unpopulated. The result is a KeyError as I attempt to parse the content into a csv. Would love any advice!

Thanks.

Update: thanks everyone! I'm now receiving a 'NoneType' error for (manufacturer):

import urllib2, json, csv, sys, os, codecs, re

from collections import defaultdict

output = 'bb.csv'

csv_writer = csv.writer(open(output, 'w'))

header = ['sku', 'name', 'description', 'image', 'manufacturer', 'upc', 'department', 'class', 'subclass']

csv_writer.writerow(header)

i=1

while i<101:

print i

bb_url = urllib2.Request("http://api.remix.bestbuy.com/v1/products(sku=*)?show=sku,name,description,image,manufacturer,upc,department,class,subclass&format=json&sort=sku.asc&page=" + str(i) + "&pageSize=100&apiKey=*****************")

bb_json = json.load(urllib2.urlopen(bb_url))

print bb_json

for product in bb_json['products']:

row = []

row.append(product['sku'])

if product['name']:

row.append(str((product['name']).encode('utf-8')))

else:

row.append("")

row.append(str(product.get('description',"")))

row.append(str(product['image'])+ " ")

if product['name']:

row.append(str(product.get('manufacturer',"").encode('utf-8')))

else:

row.append("")

row.append(str(product.get('upc','').encode('utf-8')))

row.append(str((product['department']).encode('utf-8')))

row.append(str((product['class']).encode('utf-8')))

row.append(str((product['subclass']).encode('utf-8')))

csv_writer.writerow(row)

i = i+1

解决方案

You can use your_dict.get(key, "default value") instead of directly referencing a key.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值