dictionary – How to use dot notation for dict in python?

dictionary – How to use dot notation for dict in python?

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

n

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

n

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.

n

To go back to a dict again:

n

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

n

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

n

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

I assume that you are comfortable in Javascript and want to borrow that kind of syntax… I can tell you by personal experience that this is not a great idea.

n

It sure does look less verbose and neat; but in the long run it is just obscure. Dicts are dicts, and trying to make them behave like objects with attributes will probably lead to (bad) surprises.

n

If you need to manipulate the fields of an object as if they were a dictionary, you can always resort to use the internal __dict__ attribute when you need it, and then it is explicitly clear what you are doing. Or use getattr(obj, key) to have into account the inheritance structure and class attributes too.

n

But by reading your example it seems that you are trying something different… As the dot operator will already look in the __dict__ attribute without any extra code.

dictionary – How to use dot notation for dict in python?

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

n

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

n

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

Leave a Reply

Your email address will not be published.