将对象转换为字典键

发布于 2025-01-23 18:54:18 字数 452 浏览 0 评论 0原文

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

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

tester = test()

dictionary = {}
dictionary[tester] = 1

print(dictionary[tester])
print(dictionary["test_key"])

输出在哪里:

>>> 1
>>> 1

我要寻找的是一种将对象自动转换为字符串之前的方法。这可能吗?

I was wondering if there is an easy way to essentially have multiple keys in a dictionary for one value. An example of what I would like to achieve is as following:

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

tester = test()

dictionary = {}
dictionary[tester] = 1

print(dictionary[tester])
print(dictionary["test_key"])

where the output would be:

>>> 1
>>> 1

What I'm looking for is a way to automatically convert the object to a string before its used as a key. Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

子栖 2025-01-30 18:54:18

就个人而言,我认为最好将对象明确地施放到字符串上,例如

dictionary[str(tester)] = 1

,如果您 确实 真的 确保要执行此操作,定义__哈希____ 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

这将输出:

1
1

Personally, I think it's better to explicitly cast the object to a string, e.g.

dictionary[str(tester)] = 1

That being said, if you're really really REALLY sure you want to do this, define the __hash__ and __eq__ dunder methods. No need to create a new data structure or change the existing code outside of the class definition:

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

This will output:

1
1
挽清梦 2025-01-30 18:54:18

几乎可以肯定的是,您不应该这样做。只需使用字典[str(tester)]。它更可读,令人惊讶,只有五个字符要写。

但是,如果您坚持认为,这是我能想到的最好的

class StrKeyedDict(dict):
    def __getitem__(self, key):
        return super().__getitem__(str(key))
    def __setitem__(self, key, value):
        super().__setitem__(str(key), value)
    # ... do all the other methods that mess with the key

class Test:
    key="test_key"

    def __str__(self):
        return self.key

tester = Test()
dictionary = StrKeyedDict()
dictionary[tester] = 1
print(dictionary["test_key"])
# => 1

It is almost certain you should not do this; just use dictionary[str(tester)]. It is more readable, less surprises, only five characters more to write.

If you insist though, this is the best I can think of

class StrKeyedDict(dict):
    def __getitem__(self, key):
        return super().__getitem__(str(key))
    def __setitem__(self, key, value):
        super().__setitem__(str(key), value)
    # ... do all the other methods that mess with the key

class Test:
    key="test_key"

    def __str__(self):
        return self.key

tester = Test()
dictionary = StrKeyedDict()
dictionary[tester] = 1
print(dictionary["test_key"])
# => 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文