Access Dictionary Keys As Object Attributes
By Sudheer S
You access Python dictionary keys using the syntax:
my_dicy[my_key]
For example:
>>> my_dict = {'food': 'idly'}
>>> my_dict['food']
'idly'
Sometimes, you might want to access the dictionary keys using:
my_dict.my_key
syntax. If you do this is what happens:
>>> my_dict.food
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'})
>>> my_dict.food
'idly'