Categories
Python Answers

How to access dict keys like an attribute with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *