Python:默认字典键以避免 KeyError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24814024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: default dict keys to avoid KeyError
提问by Kenfucious
Fairly new to python, novice developer, first time caller
Python 新手,新手开发人员,第一次调用
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!
我正在调用一些 JSON 并将相关数据解析为 csv。我不知道如何用默认键填充中间的 json Dict 文件,因为很多都没有填充。结果是 KeyError 当我尝试将内容解析为 csv 时。会喜欢任何建议!
Thanks.
谢谢。
Update: thanks everyone! I'm now receiving a 'NoneType' error for (manufacturer):
更新:谢谢大家!我现在收到(制造商)的“NoneType”错误:
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
采纳答案by Stack of Pancakes
You can use your_dict.get(key, "default value")
instead of directly referencing a key.
您可以使用your_dict.get(key, "default value")
而不是直接引用键。
回答by Eugen
You could use syntax like this: product.get("your field", "default value")
你可以使用这样的语法: product.get("your field", "default value")
回答by Serendipity
Don't use the "default" argument name. For example, if we want 1.0 as default value,
不要使用“默认”参数名称。例如,如果我们想要 1.0 作为默认值,
rank = dict.get(key, 1.0)
For more details: TypeError: get() takes no keyword arguments
有关更多详细信息: TypeError: get() 不接受关键字参数
回答by Alceu Rodrigues de Freitas Jun
If you can't define a default value and want to do something else (or just omit the entry):
如果您无法定义默认值并想做其他事情(或只是省略条目):
if key in dict:
rank = dict[key]
else:
# do something or just skip the else block entirely