-1

Say I had a class called Example, it conforms to Hashable via its ID attribute.

I have an Example object exam1, with ID = 6 and name = "goon". I set a dictionary entry dict[exam1] = 7.

Then lets say I had another example object with the same ID, but different data inside. Let's call it exam2, with ID = 6, name = "pie".

If I set dict[exam2] = 8, this would index to the same entry as before because their IDs are the same. However, would the key be updated to reference exam2? so dict.keys would contain reference to exam2, not exam1.

timbre timbre
  • 12,648
  • 10
  • 46
  • 77
anon12345
  • 21
  • 2
  • Where is the question? – D3vtr0n Dec 06 '21 at 17:13
  • 1
    Using reference types (classes) as dictionary keys *and* mutating their properties after insertion into a dictionary (or set) is a bad idea, see for example https://stackoverflow.com/q/55674205/1187415. – Martin R Dec 06 '21 at 19:41
  • Does this answer your question? [Convert Django Model object to dict with all of the fields intact](https://stackoverflow.com/questions/21925671/convert-django-model-object-to-dict-with-all-of-the-fields-intact) – neowinston Dec 07 '21 at 20:01

1 Answers1

1

Dictionary will contain instance of exam1, not exam2. Reason: as the documentation states

Update an existing value by assigning a new value to a key that already exists in the dictionary.

In other words, the assignment dict[x] = y can modify the value, but will never modify the key, it can only add it (if the key is not yet in dictionary) or remove it (if the value is nil).

But as someone mentioned above, this is a really bad idea. The meaning of Hashable is

Hashing a value means feeding its essential components into a hash function, represented by the Hasher type. Essential components are those that contribute to the type’s implementation of Equatable. Two instances that are equal must feed the same values to Hasher in hash(into:), in the same order.

And that takes us to the meaning of Equatable (which you will also have to implement as a part of conforming to Hashable:

Equality implies substitutability—any two instances that compare equally can be used interchangeably in any code that depends on their values.

So when you defined your Hashable, as "ID only", you state that name is not an essential component and that exam1 == exam2 (even though their name property has different values). This is legal from the language perspective, but a huge potential to bugs and issues in the future.

timbre timbre
  • 12,648
  • 10
  • 46
  • 77