这可能是一个非常基本的问题,但我浏览了关于异常的python文档,但找不到它。
我正在尝试从字典中读取一堆特定值,并将这些值插入另一个字典中。
for item in old_dicts:
try:
new_dict['key1'] = item['dog1'][0:5]
new_dict['key2'] = item['dog2'][0:10]
new_dict['key3'] = item['dog3'][0:3]
new_dict['key4'] = item['dog4'][3:11]
except KeyError:
pass
现在,如果Python在['dog1']遇到键错误,它似乎会中止当前迭代并转到old_dicts中的下一个项目。我希望它转到循环中的下一行。我是否必须为每一行插入异常指令?
答案 0 :(得分:1)
使它成为一个功能:
def newdog(self, key, dog, a, b)
try:
new_dict[key] = item[dog][a:b]
except KeyError:
pass
我没有运行上面的代码,但这样的东西应该有效,模块化。或者你可以做的是准备它,以便它检查所有值并删除不在字典中的所有值,但这可能是代码比每行的异常更多。
答案 1 :(得分:1)
for item in old_dicts:
for i, (start, stop) in enumerate([(0,5), (0,10), (0,3), (3,11)], 1):
try:
new_dict['key' + str(i)] = item['dog' + str(i)][start:stop]
except KeyError:
pass
答案 2 :(得分:1)
假设您知道密钥中的值是有效的,为什么不一起放弃所有异常并检查密钥?
for item in old_dicts:
if 'dog1' in item:
new_dict['key1'] = item['dog1'][0:5]
if 'dog2' in item:
new_dict['key2'] = item['dog2'][0:10]
if 'dog3' in item:
new_dict['key3'] = item['dog3'][0:3]
if 'dog4' in item:
new_dict['key4'] = item['dog4'][3:11]
答案 3 :(得分:0)
是的,你这样做。看起来会很麻烦和不愉快,但每次调用都需要一个异常处理程序。
也就是说,你可以用不同的方式编写代码,让自己的生活更轻松。考虑一下:
def set_new_dict_key(new_dict, key, item, path): try: for path_item in path: item = item[path_item] except KeyError: pass else: new_dict[key] = item for item in old_dicts: set_new_dict_key(new_dict, 'key1', item, ['dog1', slice(0, 5)]) set_new_dict_key(new_dict, 'key2', item, ['dog2', slice(0, 10)]) set_new_dict_key(new_dict, 'key3', item, ['dog3', slice(0, 3)]) set_new_dict_key(new_dict, 'key4', item, ['dog4', slice(3, 11)])
答案 4 :(得分:0)
是的,你会的。最佳做法是尽可能减少try
块。只编写try
块中可能出现异常的代码。请注意,else
和try
语句也有一个except
,只有在没有异常的情况下运行时才会执行:
try:
// code that possibly throws exception
except Exception:
// handle exception
else:
// do stuff that should be done if there was no exception