mo-dots: Dot-Access to Python Dictionaries

10.685.25166 · active · verified Thu Apr 16

mo-dots is a Python library that provides 'dot-access' functionality to dictionary-like data structures, similar to JavaScript objects. It boxes JSON-like data into a `Data` object, offering null-safe attribute access and a consistent interface. The library aims to be a more consistent and easier-to-use replacement for standard Python dictionaries, facilitating data transformation tasks. It is actively maintained, with the current version being 10.685.25166.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create `Data` objects, access nested properties using dot notation and path strings, perform path assignments, and handle the specialized path accumulation with `+=`. It also highlights the crucial step for JSON serialization using `from_data`.

import json
from mo_dots import Data, to_data, from_data

# Create a Data object directly
d = Data(a=1, b={'c': 2, 'd': [3, 4]})
print(f"Initial Data object: {d}")

# Access with dot notation (null-safe)
print(f"d.a: {d.a}")
print(f"d.b.c: {d.b.c}")
print(f"d.b.e: {d.b.e} (returns Null, not KeyError)")

# Path assignment
d['x.y.z'] = 99
print(f"After path assignment: {d}")

# Path accumulation with +=
d.stats.count += 1 # Initializes to 0 then adds 1
d.stats.items += ['apple'] # Initializes to [] then appends
d.stats.items += ['banana']
print(f"After path accumulation: {d}")

# Convert an existing dictionary
my_dict = {'user': {'name': 'Alice', 'id': 123}}
data_from_dict = to_data(my_dict)
print(f"Data from dict: {data_from_dict.user.name}")

# Serialize to JSON (requires from_data)
try:
    json.dumps(d) # This will raise TypeError without default=from_data
except TypeError as e:
    print(f"Caught expected TypeError during direct JSON serialization: {e}")

json_output = json.dumps(d, default=from_data)
print(f"JSON output: {json_output}")
assert json.loads(json_output) == {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'x': {'y': {'z': 99}}, 'stats': {'count': 1, 'items': ['apple', 'banana']}}

view raw JSON →