set.add() doesn't replace equal element

Chris Angelico rosuav at gmail.com
Fri Dec 30 16:58:20 EST 2022


On Sat, 31 Dec 2022 at 08:42, Ian Pilcher <arequipeno at gmail.com> wrote:
>
> I just discovered this behavior, which is problematic for my particular
> use.  Is there a different set API (or operator) that can be used to
> add an element to a set, and replace any equal element?
>
> If not, am I correct that I should call set.discard() before calling
> set.add() to achieve the behavior that I want?
>

Use a dictionary. Initially, map everything to itself. You can then
replace things with the new keys:

>>> stuff = {}
>>> stuff[1] = 1
>>> stuff[4] = 4
>>> stuff[True] = True
>>> stuff[2] = 2
>>> stuff[4.0] = 4.0
>>> stuff
{1: True, 4: 4.0, 2: 2}

To see what's in your set, look at the dictionary's values. They will
replace any equal elements, leaving the keys unchanged.

ChrisA


More information about the Python-list mailing list