Dotmap
Dotmap is a Python library that provides a dot-access dictionary, allowing dictionary keys to be accessed as object attributes (e.g., `m.key` instead of `m['key']`). It supports dynamic hierarchy creation, ordered iteration, and can be initialized from or converted back to standard Python dictionaries. The current stable version is 1.3.30, and it maintains an active release cadence with regular updates.
Warnings
- gotcha Accessing a non-existent key in a DotMap (e.g., `m.non_existent_key`) will dynamically create an empty DotMap for that key, rather than raising a KeyError or returning None. This is a core feature for dynamic expansion but can be unexpected if you intend to check for key existence without modification.
- gotcha When converting a DotMap initialized from a nested dictionary back to a regular dictionary using `toDict()`, some internal DotMap instances might persist as values, or unexpected 'size'/'shape' keys might be added if they were implicitly created or managed by DotMap's internal mechanisms, leading to inconsistencies.
- gotcha Dictionary keys that conflict with Python's reserved keywords or built-in object attributes (e.g., 'items', 'keys', 'values', 'clear', 'copy', or leading with special characters) can lead to unexpected behavior or errors when accessed via dot notation. For instance, `m.items` would access the DotMap's `items()` method, not a key named 'items'.
- gotcha When subclassing `DotMap`, initializing `super().__init__(...)` with nested dictionaries might not always behave as expected, sometimes failing to properly convert nested dictionaries into DotMap instances within the subclass.
Install
-
pip install dotmap
Imports
- DotMap
from dotmap import DotMap
Quickstart
from dotmap import DotMap
# Initialize an empty DotMap
m = DotMap()
# Assign values using dot notation
m.name = 'Joe'
# Dynamically create nested structures
m.people.john.age = 32
m.people.john.job = 'coder'
# Append to lists (dynamically created)
m.list.append(1)
m.list.append(2)
m.list.append(3)
# Access values
print(f"Name: {m.name}")
print(f"John's Age: {m.people.john.age}")
print(f"List: {m.list}")
# Convert back to a standard dictionary
regular_dict = m.toDict()
print(f"Converted to dict: {regular_dict}")