1

I have the below dictionary:

>>> dict1={'a':1,'b':2}
>>>
>>>
>>> dict1['a']
1
>>>

Q: Is there a way to retrieve the value of key (in the above dictionary), using the hash value of the key? If I print 'a'.__hash__ , I get:

>>> print 'a'.__hash__
<method-wrapper '__hash__' of str object at 0x00000000021AA0F8>
>>>

Q2: Why not do a key lookup directly rather than converting the key to a hash value and then do the lookup? I read that using hash makes it faster.

1
  • There is not necessary a one-to-one mapping between the hash and the key, it depends on the implementation and on the key. Of course Python manages to do the lookup, and I suggest you download the C source and read Objects/dictnotes.txt and Objects/dictobject.c. Then you will probably decide it is better to let Python do it. Commented Feb 1, 2017 at 9:08

1 Answer 1

2

You don't need to retrieve the value using hash by yourself, Python dict do that for you. Python dict use hash internally.

from https://docs.python.org/3/library/stdtypes.html#typesmapping

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.

Sign up to request clarification or add additional context in comments.

1 Comment

i understand what you say, but i need to know if there is a way to get the value of a key(in a dict) using the hash of the key ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.