AttrDict module in Python
The AttrDict
module in Python is a third-party library that provides a dictionary-like object that allows you to access its keys as attributes. This means that instead of using the traditional dictionary syntax of my_dict['key']
, you can use the dot notation of my_dict.key
.
Here's an example of how to use the AttrDict
module:
from attrdict import AttrDict
my_dict = AttrDict({'name': 'John', 'age': 30})
print(my_dict.name) # Output: John
print(my_dict.age) # Output: 30
# You can also access the keys using the traditional dictionary syntax
print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 30
# You can add new keys to the AttrDict
my_dict.city = 'New York'
print(my_dict.city) # Output: New York
# You can also update the values of existing keys
my_dict.age = 35
print(my_dict.age) # Output: 35
Another way to create an AttrDict
is by subclassing it:
from attrdict import AttrDict
class MyDict(AttrDict):
pass
my_dict = MyDict({'name': 'John', 'age': 30})
print(my_dict.name) # Output: John
print(my_dict.age) # Output: 30
You can also use the AttrDict
module to convert a nested dictionary into an AttrDict
:
from attrdict import AttrDict
nested_dict = {'person': {'name': 'John', 'age': 30}}
my_dict = AttrDict(nested_dict)
print(my_dict.person.name) # Output: John
print(my_dict.person.age) # Output: 30
Overall, the AttrDict
module provides a convenient way to access dictionary keys as attributes, which can make your code more readable and easier to work with.