在Python中使用对象作为字典中的关键字 - 哈希函数 [英] Using object as key in dictionary in Python - Hash function

查看:162
本文介绍了在Python中使用对象作为字典中的关键字 - 哈希函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个对象作为Python中的字典的键值。我遵循一些其他帖子的建议,我们需要实现2个功能:哈希 eq

I am trying to use an object as the key value to a dictionary in Python. I follow the recommendations from some other posts that we need to implement 2 functions: hash and eq

那个,我期待以下的工作,但没有。

And with that, I am expecting the following to work but it didn't.

class Test:
    def __init__(self, name):
        self.name = name

    def __hash__(self):
        return hash(str(self.name))

    def __eq__(self, other):
        return str(self.name) == str(other,name)


def TestMethod():
    test_Dict = {}

    obj = Test('abc')
    test_Dict[obj] = obj

    print "%s" %(test_Dict[hash(str('abc'))].name)       # expecting this to print "abc" 

但它是给我一个关键错误信息:

But it is giving me a key error message:

KeyError: 1453079729188098211

有人可以帮助启发我为什么这不行吗?

Can someone help enlightening me why this doesn't work?

推荐答案

映射的元素不是由他们的哈希访问,即使它们的哈希用于将它们放在映射中。在为存储和检索索引时,您必须使用相同的值。

Elements of a mapping are not accessed by their hash, even though their hash is used to place them within the mapping. You must use the same value when indexing both for storage and for retrieval.

这篇关于在Python中使用对象作为字典中的关键字 - 哈希函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆