About Me

Friday, March 4, 2011

Nice Python function for dictionaries

Not my code but found this whilst browsing for some functionality. Basically allows you to use .dot formatting when accessing keys in a dict:

class dotdictify(dict):
    marker = object()
    def __init__(self, value=None):
        if value is None:
        elif isinstance(value, dict):
            for key in value:
                self.__setitem__(key, value[key])
            raise TypeError, 'expected dict'

    def __setitem__(self, key, value):
        if isinstance(value, dict) and not isinstance(value, dotdictify):
            value = dotdictify(value)
        dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        found = self.get(key, dotdictify.marker)
        if found is dotdictify.marker:
            found = dotdictify()
            dict.__setitem__(self, key, found)
        return found

    __setattr__ = __setitem__
    __getattr__ = __getitem__

Now we can use '.' rather than having to use standard ['key'] syntax: eg:

life = {'bigBang' :  {'stars':  {'planets': {} }}}

life = dotdictify(life)

print life.bigBang.stars.planets
instead of:
print life['bigBang']['stars']['planets']

life.bigBang.stars.planets.earth = { 'singleCellLife' : {} }
print life.bigBang.stars.planets

Ok, so it's just syntax candy, but does makes things easier to read in code.

No comments:

Post a Comment