Reputation: 7839
I have a dictionary d
which stores some information about objects:
class A:
def __init__(self, x):
self.x = x
a = A(1)
b = A(1)
c = 'hello world'
e = [1, 2, 3]
d = {a: 'a', b: 'b', c: 'c', e: 'e'}
Two questions arise:
Upvotes: 3
Views: 68
Reputation: 48120
To be used as a dictionary key, an object must support the hash
function (e.g. through __hash__
), equality comparison (e.g. through __eq__
or __cmp__
), and must satisfy the correctness condition above.
That said, the simple answer to why lists cannot be used as dictionary keys is that lists do not provide a valid __hash__
method.
Please refer Why Lists Can't Be Dictionary Keys? for detailed information.
But you can use tuple()
object instead as key
as tuples are hashable. Hence, it is valid to do:
>>> e = (1, 2, 3)
>>> d = {a: 'a', b: 'b', c: 'c', e: 'e'}
Upvotes: 2