How to use dot notation for dict in python?

后端 未结 7 1581
醉话见心
醉话见心 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:40

    This functionality already exists in the standard libraries, so I recommend you just use their class.

    >>> from types import SimpleNamespace
    >>> d = {'key1': 'value1', 'key2': 'value2'}
    >>> n = SimpleNamespace(**d)
    >>> print(n)
    namespace(key1='value1', key2='value2')
    >>> n.key2
    'value2'
    

    Adding, modifying and removing values is achieved with regular attribute access, i.e. you can use statements like n.key = val and del n.key.

    To go back to a dict again:

    >>> vars(n)
    {'key1': 'value1', 'key2': 'value2'}
    

    The keys in your dict should be string identifiers for attribute access to work properly.

    Simple namespace was added in Python 3.3. For older versions of the language, argparse.Namespace has similar behaviour.

提交回复
热议问题