Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Python hash lists using ID?

When using a dictionary in Python, the following is impossible:

d = {}
d[[1,2,3]] = 4

since 'list' is an unhashable type. However, the id function in Python returns an integer for an object that is guaranteed to be unique for the object's lifetime.

Why doesn't Python use id to hash a dictionary? Are there drawbacks?

like image 666
sdasdadas Avatar asked May 26 '13 05:05

sdasdadas


People also ask

Is ID a hash?

A transaction hash/id is a unique string of characters that is given to every transaction that is verified and added to the blockchain. In many cases, a transaction hash is needed in order to locate funds.

What is the difference between id and hash in Python?

Unequal objects may have the same hash values. Equal objects need to have the same id values. Whenever obj1 is obj2 is called, the id values of both objects is compared, not their hash values.

Why Python lists should not be used as keys for a hash table?

You cannot use a list as a key because lists are mutable. Since they are mutable, they cannot be hashable (like strings and tuples) are.

Which object can not be hashable in Python?

All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable. Objects which are instances of the user-defined class are hashable by default, they all compare unequal, and their hash value is their id().


1 Answers

The reason is right here (Why must dictionary keys be immutable)

Some unacceptable solutions that have been proposed:

  • Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.:

    mydict = {[1, 2]: '12'}

    print mydict[[1, 2]]

would raise a KeyError exception because the id of the [1, 2] used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ==, not using is.

like image 76
jamylak Avatar answered Sep 23 '22 06:09

jamylak