使用点表示法从嵌套的python字典中检索值 [英] Retrieving values from nested python dicts with dot notation

查看:96
本文介绍了使用点表示法从嵌套的python字典中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在我的一个项目中使用ConfigObj来具有基于结构化文本的配置文件,而且非常简洁. 它返回的数据结构是普通的dict类型,在我的情况下,它可能包含许多其他dict作为值,它们本身也可能包含dict,依此类推. 我正在寻找一种用Python将主要字典与类包装在一起的最Python方式,以实现类似于 getattr 的东西,以点表示法递归检索项目.像这样:

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

不幸的是,这仅适用于第一层.如果我要调用的键的值也是L2 dict,并且递归地传递到内部层,我实际上希望这是递归的.

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.

类似这样的通话:

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?

我的问题与建议的重复内容略有不同.我知道如何使用 getattr 进行普通命令.我想知道如何将其用于嵌套字典.我认为这不是一个幼稚的问题.

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.

推荐答案

好吧,我在建议的线程中添加了更多内容,而我实际上找到了一个不错的解决方案,那就是使用此程序包:

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

这篇关于使用点表示法从嵌套的python字典中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆