我正在尝试使用键-可哈希对象从字典中获取值。不幸的是,即使字典中存在具有相同哈希值的键,我也会得到KeyError:
#structures.py
class TransactionDesignation:
def __init__(self, gd, id, child_of):
self.id = id
self.child_of = child_of
self.gd = gd
def __key(self):
return (self.id, self.child_of, self.gd)
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
return self.id == other.id and self.child_of == other.child_of and self.gd == other.gd
def __str__(self):
return "Transaction id='{}', childOf='{}', gd='{}', hash='{}'".format(self.id, self.child_of, self.gd, self.__hash__())
#main.py
#TRANSACTIONS is some enum value
logs[TRANSACTIONS] = {}
...
transaction_designation = TransactionDesignation(gd, id, child_of)
#Transaction is added to the logs dictionary with the key transaction_designation
...
last_finished_transaction_designation = transaction_designation
print("Transactions:")
for key, value in logs[TRANSACTIONS].items():
print(str(key))
print("Last finished transaction:")
print(str(last_finished_transaction_designation))
print(last_finished_transaction_designation in logs[TRANSACTIONS])
transaction = logs[TRANSACTIONS][last_finished_transaction_designation]
返回Transactions:
...
Transaction id='3916', childOf='3317', gd='test1', hash='-4959730785004793724'
Transaction id='3917', childOf='3318', gd='test1', hash='-7583793915122604655'
Last finished transaction:
Transaction id='3917', childOf='3318', gd='test1', hash='-7583793915122604655'
False
transaction = logs[TRANSACTIONS][last_finished_transaction_designation]
KeyError: <structures.TransactionDesignation object at 0x7fdd6145f3a0>
你知道为什么这个键在字典里找不到吗?哈希是相同的,但仍然有KeyError可见。
[编辑]
我检查了last_finished_transaction_designation的地址和字典中最后保存位置的键,它们是相同的。
我在实现这个机制的过程中犯了一个错误。@Jasonharper,我说不需要更多代码是错误的。问题在这里:
transaction_designation = TransactionDesignation('test1', '3917', None)
logs[TRANSACTIONS][transaction_designation] = transaction
#...
transaction_designation.child_of = '3318'
last_finished_transaction_designation = transaction_designation
我更改了密钥,而没有想到它实际上是被禁止的。更改后,我无法通过旧密钥或新密钥获得此交易。
解决方案:
transaction_designation = TransactionDesignation('test1', '3917', None)
logs[TRANSACTIONS][transaction_designation] = transaction
#...
transaction = logs[TRANSACTIONS].pop(transaction_designation)
transaction_designation.child_of = '3318'
logs[TRANSACTIONS][transaction_designation] = transaction
last_finished_transaction_designation = transaction_designation
这样的实现不会出错。