Search code examples
pythondefaultdictpython-2.4

Alternatives For DefaultDict


Unfortunately, for me, I need to make a script backward compatible w/Python 2.4, and defaultdict doesn't exist in 2.4 version.

What can be an alternative for it?

The data structure for a given key is a list of:

[{'red': (12, 1, 12), 'white': (30, 2, 60), 'blue': (8, 1, 4), 'orange': (9, 4, 8), 'black': (10, 12, 4)}]

EDIT: Adding usage info. First I build the default dict with:

defDict[key1].append(... ...)

Then it's passed to several methods for key:val(list) lookups and key deletion.

Specifically for deletion:

        if len(defDict[key1][0]) == 0:
            del defDict[key1]

EDIT: error on NoneType

        print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        print defDict[key]
        print "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
        if len(defDict[key][0]) == 0:
            #del defDict[key]

Error:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
None
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
if len(defDict[key][0]) == 0:
TypeError: 'NoneType' object has no attribute '__getitem__'

I think the error comes from key:

        print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        print defDict[key]
        print "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"

Output:

       xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       None
       yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Solution

  • You can implement your own defaultdict in a pretty straightforward manner.

    def defaultdict(default_type):
        class DefaultDict(dict):
            def __getitem__(self, key):
                if key not in self:
                    dict.__setitem__(self, key, default_type())
                return dict.__getitem__(self, key)
        return DefaultDict()
    
    
    list_dict = defaultdict(list)
    list_dict['a'].append(1)
    print list_dict # {'a': [1]}