简体   繁体   English

python表中的keyerror

[英]keyerror in python table

I'm confused about the code below: 我对以下代码感到困惑:

class Table(object):
    def __init__(self):
        self.d = collections.defaultdict(dict)
    def add(self, row, col, val):
        self.d[row][col] = val
    def get(self, row, col, default=None):
        return self.d[row].get(col, default)
    def incol(self, col, val):
        for x,y in self.d.iteritems():
            if y[col]==val:
                wholerow=y
        return wholerow.values()

After I created table, I cannot use the "incol" function to get all the values. 创建表后,无法使用“ incol”函数来获取所有值。 It always give me key error. 它总是给我关键错误。 However, when I just use the same code without using function, I can get what I want. 但是,当我只使用相同的代码而不使用函数时,我可以得到想要的东西。 What happened to my code.... 我的代码发生了什么...。

The above code does not "always give me key error" ("always" being the word I am disputing here). 上面的代码并不“总是给我键错误”(“总是”是我在这里争论的词)。 For example, consider the following code: 例如,考虑以下代码:

foo = Table()
foo.add("row_1", "col_1", "col_1_value")
foo.add("row_1", "col_2", "col_2_value")
print foo.get("row_1", "col_1")
print foo.incol("col_1", "col_1_value")

This works without any errors and produces the following output: 这可以正常工作,并产生以下输出:

col_1_value
['col_2_value', 'col_1_value']

However, if you try to pass the name of a non-existent column to incol , you will get a KeyError . 但是,如果你试图通过一个不存在的列名incol ,你会得到一个KeyError For example, if you append the following line to the above code: 例如,如果将以下行添加到上面的代码中:

print foo.incol("i do not exist", "my imaginary value")

You will end up with an error message resembling the following: 您最终将收到类似于以下内容的错误消息:

Traceback (most recent call last):
File "./stack_overflow-2013-03-14.py", line 21, in <module>
    print foo.incol("i do not exist", "my imaginary value")
File "./stack_overflow-2013-03-14.py", line 12, in incol
    if y[col]==val:
KeyError: 'i do not exist'

An example implementation of incol that can handle such situations is: 可以处理这种情况的incol示例实现为:

def incol(self, col, val):
    result = None
    for x,y in self.d.iteritems():
        if col in y and y[col]==val:
            result = y.values()
            break
    return result

Now, if you run the following lines: 现在,如果您运行以下行:

foo = Table()
foo.add("row_1", "col_1", "col_1_value")
foo.add("row_1", "col_2", "col_2_value")
print foo.get("row_1", "col_1")
print foo.incol("col_1", "col_1_value")
print foo.incol("i do not exist", "my imaginary value")
print foo.incol("i do not exist", None)

You get: 你得到:

col_1_value
['col_2_value', 'col_1_value']
None
None

You can also use the following implementation of incol as suggested by Martijn Pieters: 您还可以使用Martijn Pieters建议的以下incol实现:

def incol(self, col, val):
    result = None
    for x,y in self.d.iteritems():
        if y.get(col)==val:
            result = y.values()
            break
    return result

But in this case if you pass a non-existent col name and val = None , then it will match any row. 但是在这种情况下,如果您传递不存在的col名称并且val = None ,那么它将匹配任何行。 The corresponding output will be: 相应的输出将是:

col_1_value
['col_2_value', 'col_1_value']
None
['col_2_value', 'col_1_value']

Maybe this is the behavior you want for your application. 也许这就是您想要的应用程序行为。 That is for you to decide. 那是你决定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM