Why is there no lookup method for Python sets?
<p>In Python, objects can be equal despite not being the same object (<code>==</code> vs. <code>is</code>). Consider the following sequence for arbitrary objects <code>obj1</code> and <code>obj2</code>.</p>

<pre><code>assert obj1 == obj2
assert obj1 is not obj2
s = set((obj1,))
del obj1
</code></pre>

<p>Is there a general and efficient method to obtain <code>obj1</code> from <code>s</code> and <code>obj2</code> (for arbitrarily large sets <code>s</code> happening to contain an object that is equal to the one being looked up)? (It seems that constructs relying on <code>set.intersect</code>ing singleton <code>set</code>s are not reliable.)</p>

<p>If not, why?</p>

<p>The obvious alternative is to use a <code>dict</code> where each key is stored as its own value. It's not clear how much memory that approach wastes compared to the prospective <code>set</code>-based approach.</p>

<p>No, sets are not mappings, If <code>obj1 == obj2</code>, it <em>should not matter</em>. Sets are there to test membership and to hold unique <em>values</em> (as defined by equality), not to map back to specific objects. Use a dictionary for that instead.</p>

<p>Otherwise, you'd have to iterate and pick the one object that is equal:</p>

<pre><code>obj1 = next(ob for ob in s if ob == obj2)
</code></pre>

<p>Sets in Python were borne out of the <code>dict</code> type, in that before sets were added (in 2.3 in the form of the <a href="https://docs.python.org/2/whatsnew/2.3.html#pep-218-a-standard-set-datatype" rel="nofollow"><code>sets</code> module</a>, then as a <a href="https://docs.python.org/2/whatsnew/2.4.html#pep-218-built-in-set-objects" rel="nofollow">built-in type</a>), you used dictionaries that mapped all keys to <code>None</code> to track unique values. Adding 'lookup' functionality would undo this specialisation; there is no need to add functionality to sets that dictionaries already offer, especially since dictionaries have since grown many other set features such as set algebra operations.</p>

python set