Towards understanding dictionaries

◇◆丶佛笑我妖孽 提交于 2019-12-01 22:49:46
John Coleman

A simple Python shell experiment to show that different dictionaries can use the same key:

>>> my_dict_1 = {'foo':1}
>>> my_dict_2 = {'foo':2}
>>> my_dict_1,my_dict_2
({'foo': 1}, {'foo': 2})

This is a good discussion of how it is implemented. The key point is that each dictionary is allocated its own portion of memory (which can of course grow as needed). The exact same hash function is used for both dictionaries, but is being used to probe different areas in memory.

id(...)

id(object) -> integer

Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)

Above is the id doc string, it says that object's identity is object's memory address, so we can use the id function to see the variable's memory address:

In your program, I can see the address like this:

def main():
    my_dict_1 = {}
    my_dict_1['foo'] = 1
    my_dict_2 = {}
    my_dict_2['foo'] = 2
    print(hex(id(my_dict_1['foo'])))
    print(hex(id(my_dict_2['foo'])))

if __name__ == '__main__':
    main()

This program output this:

0x9a33e0
0x9a3400

We can see that my_dict_1['foo'] and my_dict_2['foo'] have different memory address.

So I think the two dicts should use the same hash function, but the variable's memory address should be the sum of the hash value and a base value. In this way, the two variable will be stored in the different memory areas.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!