Search code examples
pythondictionaryconfigobj

Retrieving values from nested python dicts with dot notation


I'm currently using ConfigObj in a project of mine to have structured text based configuration files, and it's pretty neat. The data structure it returns is a normal dict type, which in my case could contain lots of other dicts as values, which themselves could contain dicts, and so on. I'm looking for the most pythonic way to wrap the main dict with a class in order to implement a getattr like thing to retrieve items recursively with dot notation. Something like this:

class MyDict(dict):
    def __init__(self, **kwargs):
        self.d = dict(kwargs)
    def __getattr__(self, key, default=None):
        try:
            return self.d[key]
        except AttributeError:
            print "no-oh!"
            return default

Unfortunately this only works up to layer one. I would actually like this to be recursive if the value of the key I'm calling is also a L2 dict, and recursively to inner layers.

Something like this kind of calls:

foo = MyDict(super_very_complex_nested_dict)
x = foo.a1             
y = foo.a2.b1          #a2 is a dict value
z = foo.a2.b2.c1       #a2 and b2 are dict values

What would be the smart way to do this?

edit: my question is slightly different from the suggested duplicate. I know how to use getattr for normal dicts. I want to know how to use it for nested dicts. I don't think it is a naive question.


Solution

  • Well I dag more in the suggested thread and I actually found a nice solution, that is to use this package:

    https://pypi.python.org/pypi/attrdict

    which does exactly what I want, recursion. This solves my question. It would be nice to evaluate other solutions though :)