将对象转换为字典键

Geo*_*rge 6 python string dictionary object hashmap

我想知道是否有一种简单的方法可以在字典中为一个值提供多个键。我想实现的一个例子如下:

class test:
    key="test_key"
    
    def __str__(self):
        return self.key

tester = test()

dictionary = {}
dictionary[tester] = 1

print(dictionary[tester])
print(dictionary["test_key"])
Run Code Online (Sandbox Code Playgroud)

输出将是:

>>> 1
>>> 1
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种在将对象用作键之前自动将其转换为字符串的方法。这可能吗?

Bro*_*ark 4

就我个人而言,我认为最好将对象显式转换为字符串,例如

dictionary[str(tester)] = 1
Run Code Online (Sandbox Code Playgroud)

话虽这么说,如果您真的 非常 确定要执行此操作,请定义__hash____eq__dunder 方法。无需创建新的数据结构或更改类定义之外的现有代码:

class test:
    key="test_key"
    
    def __hash__(self):
        return hash(self.key)
        
    def __eq__(self, other):
        if isinstance(other, str):
            return self.key == other
        return self.key == other.key
    
    def __str__(self):
        return self.key
Run Code Online (Sandbox Code Playgroud)

这将输出:

1
1
Run Code Online (Sandbox Code Playgroud)