正在检查OrderedDict中是否存在密钥



我正在处理从python2到python3的代码迁移。我对python中的OOP和OrderedDict没有太多经验。这是我无法解决的问题。以前也有人问过类似的问题,但似乎对本案没有任何作用。我有以下代码:

for row in rows:
new_ = dummy(row.attr, row.error_type, row.array_agg_1,
row.with_error, row.total, row.level, row.order_)
if new_ in result[n.id]: # <- never becomes true
print('I am in the if')
if new_.with_error is not None:
result[n.id][new_][1] += new_.with_error
result['total'][new_][1] += new_.with_error
else:
print('I am in the else')
if new_.with_error is not None:
result[n.id][new_] = [new_.attr, new_.with_error]

这段代码在python2中是有效的。但是,python3版本无法执行外部if语句。

result[n.id]是一个OrderedDict,看起来像这样:

#an example of result[n.id]
>>> ([(Eclipse Required Items'nce'[1540972], ['Eclipse Required Items', 1, 1, [1540972], 'nce', 1, 1681]), 
(Other Story Tab Info learned/discovered documentation and accuracy'nce'[1540973], ['Other Story Tab Info learned/discovered documentation and accuracy', 1, 1, [1540973], 'nce', 1, 1684]),
(Other (please provide detail in Comments section)'bce'[1541001], ['Other (please provide detail in Comments section', 1, 1, [1540973], 'bce', 1, 1684]
(Other Static bar information was documented'nce'[1540974], ['Other Static bar information was documented', 1, 1, [1541001], 'nce', 1, 1707])])
#type of result[n.id]
>>> <class 'collections.OrderedDict'>

new_看起来像这样:

#print(new_)
Other (please provide detail in Comments section)'bce'[1541001]
#print(type(new_))
<class 'smd.lib.asynch.calibration.dummy'>

我尝试过的东西

if str(new_) in str(result[n.id]):

然而,它在KeyError内部失败了,我不确定这是否是最好的方法。此外,它可能会破坏软件的其他功能。

if new_ in result[n.id].keys():

不起作用。我们将非常感谢为解决这一问题提供的任何帮助和指导。

dummy类如下所示:

class dummy(object):
def __init__(self, attr, error_type, path, with_error=None, total=None,
level=None, order=None):
self.attr = attr
self.error_type = error_type
self.path = path
self.with_error = with_error
self.total = total
self.level = level
self.order = order
def __cmp__(self, other):
return not (
self.attr == other.attr and self.error_type == other.error_type
and self.path == other.path
)
def __base_repr__(self):
return "{0}{1}{2}".format(self.attr, self.error_type, self.path)
def __hash__(self):
return hash(self.__base_repr__())
def __repr__(self):
return self.__base_repr__()

在Python 3中,__cmp__不再使用。您需要在类中实现__eq__并删除__cmp__

最新更新