Is there\How would you build an equivalent of python's very useful collections.defaultdict?
Imagined usage of such a container:
>>> a = collections.defaultlist(0)
>>> a[2]=7
>>> a[4]='x'
>>> a
[0,0,7,0,'x']
UPDATE: I've added a follow up question to add even more functionality to this construct
A slightly enhanced version from answer by @Finn.
class defaultlist(list):
    """List returning default value when accessing uninitialized index.
    Original implementation: http://stackoverflow.com/a/8719940/315168
    """
    def __init__(self, fx):
        self._fx = fx
    def __setitem__(self, index, value):
        while len(self) <= index:
            self.append(self._fx())
        list.__setitem__(self, index, value)
    def __getitem__(self, index):
        """Allows self.dlist[0] style access before value is initialized."""
        while len(self) <= index:
            self.append(self._fx())
        return list.__getitem__(self, index)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With