It might be easier to ignore dictionaries for a moment, and just think of sets. You can probably see how a set s
might consist of {'a', 1, some_object}
, right? And that if you tried to add 1
to this set, it wouldn't do anything (since 1
is already there)?
Now, suppose you try to add a another_object
to s
. another_object
is not 1
or 'a'
, so to see if it can be added to s
, Python will see if another_object
is equal to some_object
. Understanding object equality is a whole nother subject, but suffice it to say, there is a sensible way to go about it. If another_object == some_object
is true, then s
will remain unchanged. Otherwise, s
will consist of {'a', 1, some_object, another_object}
.
Hopefully, this makes sense to you. If it does, then just think of dictionaries as special sets. The keys of the dictionary are the entries of the set, and values of the dictionary just hold a single value for each key. Saying d['and now'] = 'completely different'
is just the same thing as deleting 'and now'
from the set, and then adding it back it again with 'completely different'
as its associated value. (This isn't technically how a dict handles __setitem__
, but it can be helpful to think of a dict as working this way. In reality, sets are more like crippled dicts than dicts are like extra powerful sets).
Of course, with dicts you should bear in mind that only hashable objects are allowed in a dict. But that is itself a different subject, and not really the crux of your question, AFAICT