将对象转换为字典键
我想知道是否有一种简单的方法可以在字典中以一个值进行多个键。我想实现的一个示例如下:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就个人而言,我认为最好将对象明确地施放到字符串上,例如
,如果您确实 真的 确保要执行此操作,定义
__哈希__
和__ eq __
dunder方法。无需创建新的数据结构或更改类定义之外的现有代码:这将输出:
Personally, I think it's better to explicitly cast the object to a string, e.g.
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:This will output:
几乎可以肯定的是,您不应该这样做。只需使用
字典[str(tester)]
。它更可读,令人惊讶,只有五个字符要写。但是,如果您坚持认为,这是我能想到的最好的
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