Menu Close

How to access dict keys like an attribute with Python?

Sometimes, we want to access dict keys like an attribute with Python.

In this article, we’ll look at how to access dict keys like an attribute with Python.

How to access dict keys like an attribute with Python?

To access dict keys like an attribute with Python, we can create a subclass of the dict class.

For instance, we write

class AttributeDict(dict):
    __slots__ = ()
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__

to create the AttributeDict subclass of dict that sets the __getattr__ and __setattr__ methods to the dict‘s __getitem__ and __setitem__ methods respectively.

Now we can manipulate dict entries like objects by creating AttributeDict instances.

Conclusion

To access dict keys like an attribute with Python, we can create a subclass of the dict class.

Posted in Python, Python Answers