Tech Chorus

Access Dictionary Keys As Object Attributes

written by Sudheer Satyanarayana on 2015-02-24

You access Python dictionary keys using the syntax:


For example:

>>> my_dict = {'food': 'idly'}
>>> my_dict['food']

Sometimes, you might want to access the dictionary keys using:


syntax. If you do this is what happens:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'food'

How can you solve this? Easy.

 pip install attrdict

How do you use the newly installed package?

>>> from attrdict import AttrDict
>>> my_dict = AttrDict({'food': 'idly'})