Michael
Michael

Reputation: 7839

Use objects as dictionary keys

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:

  1. The approach does not work for lists or for other objects whose hash does not correspond to the storage address. What can I do in that cases?
  2. Is that approach unsafe under other conditions than mentioned in question (1)?

Upvotes: 3

Views: 68

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

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

Related Questions