Is there an elegant way to keep track of sets of connected items in Python?
<p>For a certain piece of code, I needed to find a way to recognise certain aliases. Thing is, it is not known beforehand what those aliases are.</p>

<p>These are my requirements:</p>

<ul>
<li>If <em>A</em> and <em>B</em> are aliases, and <em>B</em> and <em>C</em> are aliases, <em>A</em> and <em>C</em> should be aliases as well.</li>
<li>Two sets of aliases should be merged when they are connected in any way.</li>
<li>In each set of aliases, one should be the primary alias.</li>
</ul>

<p>I use the following solution, making use of what boils down to a dictionary of sets:</p>

<pre><code>class Alias(object):
    def __init__(self, initial):
        self._set = {initial}
        self.initial = initial
    def add(self, alias):
        self._set.add(alias)
    def merge(self, other):
        self._set.update(other._set)
    def __iter__(self):
        return iter(self._set)

class AliasDict(object):
    def __init__(self):
        self._dict = {}
    def add(self, one, other):
        if one in self._dict:
            if other in self._dict: #merge!
                self._dict[one].merge(self._dict[other])
                for k in self._dict[other]:
                    self._dict[k] = self._dict[one]
            else:
                self._dict[one].add(other)
        elif other in self._dict:
            self._dict[other].add(one)
        else:
            self._dict[one] = self._dict[other] = Alias(one)
            self._dict[one].add(other)
    def get(self, n):
        return self._dict.get(n)
    def __contains__(self, s):
        return s in self._dict
</code></pre>

<p>Could this be improved upon? For example, by making use of a class in the standard library (I've searched, but I might have missed something useful.)</p>
