chunklet.common.dotdict
DotDict/DotList with Box-compatible serialization.
This module embeds code originally from dotdict3 (MIT License).
Co-authored by:
- speedyk-005
- Patrick Elmer patrick@elmer.ws (https://github.com/dotdict/dotdict3)
Modifications: added to_dict(), to_json(), to_yaml(),
to_msgpack(), to_toml(), to_csv() for backward compatibility
with the python-box API.
Classes:
-
DotDict–A dict subclass with dot-notation access and automatic nested conversion.
-
DotList–A list subclass with automatic nested dict/list conversion.
DotDict
Bases: dict
A dict subclass with dot-notation access and automatic nested conversion.
Basic usage::
>>> d = DotDict({"name": "John", "age": 30})
>>> d.name
'John'
>>> d.age
30
Nested dicts auto-convert::
>>> d = DotDict({"user": {"name": "Bob", "age": 25}})
>>> d.user.name
'Bob'
>>> d.user.age
25
Lists auto-convert to DotList::
>>> d = DotDict({"users": [{"name": "Alice"}, {"name": "Bob"}]})
>>> d.users[0].name
'Alice'
>>> isinstance(d.users, DotList)
True
Dot notation assignment::
>>> d = DotDict()
>>> d.name = "Alice"
>>> d.name
'Alice'
Methods:
-
to_dict–Recursively convert back to a plain dict.
-
to_json–Serialize to a JSON string, or write to a file if filename is given.
-
to_msgpack–Serialize to MessagePack bytes, or write to a file if filename is given.
Source code in src/chunklet/common/dotdict.py
to_dict
Recursively convert back to a plain dict.
d = DotDict({"a": {"b": 1}, "c": [{"d": 2}]}) d.to_dict() {'a': {'b': 1}, 'c': [{'d': 2}]}
to_json
Serialize to a JSON string, or write to a file if filename is given.
DotDict({"content": "Hello", "count": 3}).to_json() '{"content": "Hello", "count": 3}'
Source code in src/chunklet/common/dotdict.py
to_msgpack
Serialize to MessagePack bytes, or write to a file if filename is given.
import msgpack d = DotDict({"a": 1, "b": [2, 3]}) msgpack.unpackb(d.to_msgpack())
Source code in src/chunklet/common/dotdict.py
DotList
Bases: list
A list subclass with automatic nested dict/list conversion.
l = DotList([{"a": 1}, {"b": 2}]) l[0].a 1 l[1].b 2
Methods:
-
to_dict–Recursively convert back to a plain list.
Source code in src/chunklet/common/dotdict.py
to_dict
Recursively convert back to a plain list.
DotList([DotDict({"a": 1}), DotDict({"b": 2})]).to_dict() [{'a': 1}, {'b': 2}]