Retrieving values from nested python dicts with dot notation [duplicate]

我的未来我决定 提交于 2019-12-11 11:48:25

问题


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.


回答1:


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 :)



来源:https://stackoverflow.com/questions/34850803/retrieving-values-from-nested-python-dicts-with-dot-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!