How to use dot notation for dict in python?

batman picture batman · Apr 29, 2013 · Viewed 78.1k times · Source

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:

>>> test = dict()
>>> test['name'] = 'value'
>>> print(test['name'])
value

But I wish I could do test.name to get value. Infact I did it by overriding the __getattr__ method in my class like this:

class JuspayObject:

    def __init__(self,response):
        self.__dict__['_response'] = response

    def __getattr__(self,key): 
        try:
            return self._response[key]
        except KeyError,err:
            sys.stderr.write('Sorry no key matches')

and this works! when I do:

test.name // I get value.

But the problem is when I just print test alone I get the error as:

'Sorry no key matches'

Why is this happening?

Answer

wim picture wim · Apr 29, 2013

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.