Recursively access dict via attributes as well as index access?

前端 未结 5 1507
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 06:36

I\'d like to be able to do something like this:

from dotDict import dotdictify

life = {\'bigBang\':
           {\'stars\':
               {\'planets\': []}
         


        
5条回答
  •  天涯浪人
    2020-12-02 07:03

    Here is another solution:

    from typing import Dict, Any
    
    class PropertyTree: pass
    
    def dict_to_prop_tree(yaml_config: Dict[str, Any]) -> PropertyTree:
        tree = PropertyTree()
        for key, value in yaml_config.items():
            if type(value) == dict:
                setattr(tree, key, dict_to_obj_tree(value))
            elif type(value) == list:
                setattr(tree, key, [dict_to_obj_tree(v) for v in value])
            else:
                setattr(tree, key, value)
        return tree
    

    Then in the python console:

    d={'a': 1, 'b': 2, 'c': {'d': 4, 'e': 5, 'f': {'g': 6}, 'h': {}, 'j': 7}}
    tree=dict_to_prop_tree(d)
    tree.a
    tree.c.f.g
    

    prints the correct values

提交回复
热议问题