2

这可能是一个非常基本的问题,但是我查看了有关异常的 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 中的下一项。我希望它转到循环中的下一行。我必须为每一行插入一个异常指令吗?

4

5 回答 5

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
于 2013-06-12T05:46:32.407 回答
1

使它成为一个函数:

def newdog(self, key, dog, a, b)
    try:
        new_dict[key] = item[dog][a:b]  
    except KeyError:
        pass

我没有运行上面的代码,但类似的东西应该可以工作,模块化。或者您可以做的是准备,以便它检查所有值并删除所有不在字典中的值,但这可能比每行的异常更多的代码。

于 2013-06-12T05:45:55.720 回答
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]
于 2013-06-12T06:11:00.350 回答
0

Yes, you will. Best practice is to keep your try blocks as small as possible. Only write the code you possibly expect an exception from in the try block. Note that you also have an else for the try and except statements, that only gets executed when the try ran without an exception:

try:
    // code that possibly throws exception
except Exception:
    // handle exception
else:
    // do stuff that should be done if there was no exception
于 2013-06-12T05:52:37.037 回答
0

是的你是。看起来会很混乱且令人不快,但是您确实需要为每个调用提供一个异常处理程序。


也就是说,您可以稍微不同地编写代码,以使自己的生活更轻松。考虑一下:

def set_new_dict_key(new_dict, key, item, path):
    尝试:
        对于路径中的 path_item:
            项目 = 项目 [路径项目]
    除了 KeyError:
        经过
    别的:
        new_dict[key] = 项目

对于 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)])
于 2013-06-12T05:47:29.703 回答