Search code examples
pythoncollectionscontainersdefaultdict

defaultdict equivalent for lists


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


Solution

  • I think this would be a bit confusing to use; however, here's my first thought on how to do it:

    class defaultlist(list):
        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)
    

    This takes a callable (I think that's how defaultdict works) for the default value.

    When I run:

    a = defaultlist(int)
    print a
    a[2] = 7
    a[4] = 'x'
    print a
    

    I get back:

    []
    [0, 0, 7, 0, 'x']