Addict
Addict is a Python library that provides a dictionary subclass allowing items to be accessed and set using both attribute (dot notation) and item (square bracket) syntax. It simplifies working with deeply nested data structures. The library is currently at version 2.4.0 and demonstrates active maintenance with regular updates.
Warnings
- breaking In version 2.0.0, accessing a non-existent key via attribute (e.g., `my_dict.non_existent_key`) no longer automatically creates an empty `Dict` and adds it to the parent. It now returns an empty `Dict` but *does not* modify the original `my_dict`. To add a key, you must assign a value (e.g., `my_dict.new_key = {}`).
- gotcha Keys that are not valid Python identifiers (e.g., integers, keys with spaces or special characters) cannot be accessed or set using attribute (dot) syntax. These must still be accessed using standard item (square bracket) syntax.
- gotcha When initializing a `Dict` with an iterable containing other container types (like a list of dictionaries), `addict` clones these values and converts nested dictionaries into `Dict` instances. However, if you later assign an existing container type via attribute or item syntax, `addict` generally maintains the reference to the original object, leading to different behavior than during initial construction.
- gotcha The `freeze()` method (introduced in v2.4.0) prevents the creation or retrieval of missing keys, raising a `KeyError` or `AttributeError` instead. This changes the default 'autovivification' behavior of `addict` and can lead to unexpected errors if not handled.
Install
-
pip install addict
Imports
- Dict
from addict import Dict
Quickstart
from addict import Dict
# Create an Addict dictionary
body = Dict()
# Set nested values using dot notation
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'
print(body)
# Access values
print(body.query.filtered.query.match.description)
# Standard dict operations also work
body['metadata'] = {'source': 'API'}
print(body.metadata.source)