Reputation:
Is there a lineal python structure that preserves insertion order and uniqueness of elements at the same time? I know that sets preserve uniqueness and list insertion order. By now I will implement this behavior with a class like:
class OrderedUniqueContainer:
def __init__(self):
self._data = []
def add(self, object):
# Assuming object has neccesary __hash__ and __eq__
if object not in self._data:
self._data.append(object)
def remove(self, object):
try:
self._data.remove(object)
except ValueError:
pass
I also need to implement union and difference. Is there a built-in structure to achieve this behavior?
Upvotes: 2
Views: 283
Reputation: 51989
A dict
is insertion ordered* and guarantees uniqueness of keys. Either use a plain dict
and ignore values by convention or create a class with the desired interface.
For example, a basic set
-like class would look like this:
class OrderedUniqueContainer:
"""Set-like container of unique items maintaining insertion order"""
def __init__(self, initial=()):
self._data = dict.fromkeys(initial)
def copy(self):
"""Return a shallow copy of the set."""
clone = type(self)()
clone._data = self._data.copy()
return clone
def add(self, item):
"""Add element `item` to the set."""
self._data[item] = None
def discard(self, item):
"""Remove element `item` from the set if it is present."""
self._data.pop(item, None)
def update(self, *others: 'OrderedUniqueContainer'):
"""Update the set, adding elements from all others."""
for other in others:
self._data.update(other._data)
def union(self, *others: 'OrderedUniqueContainer'):
"""Return a new set with elements from the set and all others."""
clone = self.copy()
clone.update(*others)
return clone
# additional desired methods
*Since Python 3.6 de-facto and since Python 3.7 guaranteed.
Upvotes: 3