首页 > 解决方案 > Python字典查找具有复合键属性的值

问题描述

字典有一个自定义类作为键。我想通过使用哈希函数的值而不是对象来搜索键的存在。

下面的代码段打印无、无、无。原因是实例的eq检查。但是,我无法删除 isInstance 检查(解释器失败)

关于如何获得打印 None, object one, object 2 的结果的任何建议?

class person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def __hash__(self):
        return self.age
        
    def __eq__(self, other):
        return isinstance(other,person) and other.age == self.age
    
    def __str__(self):
        return 'name: ' + self.name + ' age: ' + self.age
    
class find:
    def run(age):
        d = {obj('hi',10) : 'one', obj('bye',20) : 'two'}
        item = d.get(age, None)
        print(item)

one = person('one',1)
two = person('two', 2)

d = {one : 'one', two: 'two'}

print(d.get(0, None))
print(d.get(1, None))
print(d.get(2, None))

标签: pythondictionary

解决方案


事实上,python 允许在同一个字典中使用相同的哈希值。

你可以试试

d = {one : 'one', two: 'two', 1: 'one'}

这不会显示错误。

如果你想知道为什么。您应该搜索python如何使用哈希表实现dict。

在你的代码中。您可以通过以下方式获得您的价值:

d[one]

或者

d.get(one, None)

推荐阅读