How to use dot notation for dict in python?

后端 未结 7 1574
醉话见心
醉话见心 2020-11-29 20:44

I\'m very new to python and I wish I could do . notation to access values of a dict.

Lets say I have test like this:

7条回答
  •  迷失自我
    2020-11-29 21:39

    In addition to this answer, one can add support for nested dicts as well:

    from types import SimpleNamespace
    
    class NestedNamespace(SimpleNamespace):
        def __init__(self, dictionary, **kwargs):
            super().__init__(**kwargs)
            for key, value in dictionary.items():
                if isinstance(value, dict):
                    self.__setattr__(key, NestedNamespace(value))
                else:
                    self.__setattr__(key, value)
    
    nested_namespace = NestedNamespace({
        'parent': {
            'child': {
                'grandchild': 'value'
            }
        },
        'normal_key': 'normal value',
    })
    
    
    print(nested_namespace.parent.child.grandchild)  # value
    print(nested_namespace.normal_key)  # normal value
    

    Note that this does not support dot notation for dicts that are somewhere inside e.g. lists.

提交回复
热议问题