在KeyError上打印dict

时间:2015-02-10 02:05:59

标签: python python-2.7 error-handling

我正在使用几个庞大的dicts列表,其中一些可能缺少项目。我得到了很多关键错误。他们告诉我坏键是什么,但是他们不会告诉我这个词有什么问题。我想要的东西相当于

foos = [{'abc': 0, 'bcd': 1}, {'abc': 2}, {'abc': 4, 'bcd': 0}]
for foo in foos:
    try:
        print foo['bcd']
    except KeyError as err:
        print 'bcd not found in ' + str(foo)

但我在哪里订阅foos,bars,beses和quxes。换句话说,我喜欢它,如果我的错误打印声明可以推断出' foo'是有问题的词典,没有我必须明确它。在处理大量词典时,我真的不愿意为每个下标提供自己的try / except块。

2 个答案:

答案 0 :(得分:2)

如果您要查找列表中字典的索引,可以使用枚举:

foos = [{'abc': 0, 'bcd': 1}, {'abc': 2}, {'abc': 4, 'bcd': 0}]
for idx, foo in enumerate(foos):
    try:
        print foo['bcd']
    except KeyError as err:
        print 'bcd not found in dictionary #' + idx

答案 1 :(得分:1)

如果您想要的是每次尝试访问不存在的密钥时打印查找的密钥及其字典,在我看来,您必须继承dict

class ErrorDict(dict):

    def __getitem__(self, key):
        try:
            val = dict.__getitem__(self, key)
        except KeyError:
            val = None
            print '{0} not found in {1}'.format(key, self)

        return val


foos = [ErrorDict(i) for i in ({'abc': 0, 'bcd': 1}, {'abc': 2}, {'abc': 4, 'bcd': 0})]
for foo in foos:
    if foo['bcd']: # If invalid, None is returned and condition will fail.
        #... all the code
        pass

# Output: bcd not found in {'abc': 2}

这似乎符合您的要求,根据我的理解,这是为了避免在代码中的任何地方使用try/except块。我不能说我建议采用这种方式,因为我没有太多经验子类dict,所以我不熟悉其潜在的陷阱。

无论如何,它适用于您的要求。如果您有任何其他问题,请拍摄。

相关问题