我今天一直在编写这个脚本,在循环数据并将其导入外部数据库方面取得了一些非常好的进展。我正在尝试对一个有问题的字段进行故障排除,但它没有多大意义。每当我试图运行它时,都会出现以下错误KeyError: 'manufacturer'
。如果我注释掉product_details['manufacturer'] = item['manufacturer']
行,脚本就会正常运行。在
不确定还需要检查什么,也不确定从这里到哪里(python新手)
我使用以下datasets/master/ecommerce/bestbuy_seo.json" rel="nofollow noreferrer">test data
import json
input_file = open ('data/bestbuy_seo.json')
json_array = json.load(input_file)
product_list = []
for item in json_array:
product_details = {"name": None, "shortDescription": None, "bestSellingRank": None,
"thumbnailImage": None, "salePrice": None, "manufacturer": None, "url": None,
"type": None, "image": None, "customerReviewCount": None, "shipping": None,
"salePrice_range": None, "objectID": None, "categories": [None] }
product_details['name'] = item['name']
product_details['shortDescription'] = item['shortDescription']
product_details['bestSellingRank'] = item['bestSellingRank']
product_details['thumbnailImage'] = item['thumbnailImage']
product_details['salePrice'] = item['salePrice']
product_details['manufacturer'] = item['manufacturer']
product_details['url'] = item['url']
product_details['type'] = item['type']
product_details['image'] = item['image']
product_details['customerReviewCount'] = item['customerReviewCount']
product_details['shipping'] = item['shipping']
product_details['salePrice_range'] = item['salePrice_range']
product_details['objectID'] = item['objectID']
product_details['categories'] = item['categories']
product_list.append(product_details)
# Let's dump it to the screen to see if it works
print json.dumps(product_list, indent=4)
我猜您的数据中有一项没有“制造商”密钥集。在
更换
项目[“制造商”]
通过
在项目。获取(“制造商”,无)
或者用默认的制造商替换它们。。。在
这不是目前的问题(item缺少键
manufacturer
,可能更多),但是由于您只是复制具有完全相同键的字段,所以可以编写如下内容。还要注意,item.get(key, None)
将以在产品中包含None
值为代价来消除此错误(因此,如果您希望代码在失败时发生严重故障,这可能是不好的)这里有两种方法可以绕过没有钥匙的字典。这两种方法都可以,但是第一种方法可能更容易使用,并且可以作为当前代码的一个插件。在
这是一种使用python的
dictionary.get()
方法来实现的方法。Here is a page with more examples of how it works。这个解决问题的方法是受当前问题的this的启发。我根据他的回答修改了你的密码。在这是使用python中的“请求原谅而不是许可”概念的第二种方法。很容易让一个缺少属性的对象失败并继续运行。尝试和期待比一堆“如果”要快得多
Here is a post about this concept.
^{pr2}$相关问题 更多 >
编程相关推荐