Filesystem-like pathing and searching for dictionaries
npx @tessl/cli install tessl/pypi-dpath@2.2.0A Python library for accessing and manipulating nested dictionaries using filesystem-like path notation. dpath enables developers to traverse, search, filter, and modify complex dictionary structures using xpath-style syntax with support for globbing patterns, providing intuitive path-based operations for hierarchical data.
pip install dpathimport dpathAccess to main functions:
from dpath import new, get, set, delete, search, values, mergeAccess to types and exceptions:
from dpath.types import MergeType, PathSegment, Filter, Glob, Path, Creator, Hints, ListIndex
from dpath.exceptions import PathNotFound, InvalidGlob, InvalidKeyName, FilteredValueAccess to configuration and version:
import dpath.options # Configuration options
import dpath.version # Version infoLegacy util module (deprecated):
import dpath.util # Deprecated - use dpath directly insteadimport dpath
# Sample nested dictionary
data = {
"users": {
"john": {"age": 30, "city": "New York"},
"jane": {"age": 25, "city": "Los Angeles"}
},
"settings": {
"theme": "dark",
"notifications": True
}
}
# Get a single value
age = dpath.get(data, "users/john/age") # Returns: 30
# Search for patterns
cities = dpath.search(data, "users/*/city")
# Returns: {'users': {'john': {'city': 'New York'}, 'jane': {'city': 'Los Angeles'}}}
# Get all matching values
all_cities = dpath.values(data, "users/*/city") # Returns: ['New York', 'Los Angeles']
# Set a new value (creates path if it doesn't exist)
dpath.new(data, "users/bob/age", 35)
# Update existing values with glob patterns
dpath.set(data, "users/*/age", 999) # Sets all user ages to 999
# Delete matching paths
dpath.delete(data, "users/john") # Removes john's entire record
# Merge dictionaries deeply
other_data = {"users": {"alice": {"age": 28}}}
dpath.merge(data, other_data) # Merges alice into existing usersdpath uses a layered architecture that separates concerns for robust path manipulation:
get, set, search, etc.) that handle user input validation and provide convenient interfacesThis design allows for powerful operations on nested data structures while maintaining type safety and providing clear error reporting.
Core functions for getting and setting values at specific paths in nested dictionaries, supporting both exact paths and glob patterns.
def get(obj, glob, separator="/", default=_DEFAULT_SENTINEL):
"""Get single value matching glob pattern."""
pass
def new(obj, path, value, separator="/", creator=None):
"""Create new path and set value, creating missing keys."""
pass
def set(obj, glob, value, separator="/", afilter=None):
"""Set value for all existing elements matching glob."""
passPowerful search capabilities for finding paths and values matching glob patterns, with support for filtering and yielding results.
def search(obj, glob, yielded=False, separator="/", afilter=None, dirs=True):
"""Search for paths/values matching glob pattern."""
pass
def values(obj, glob, separator="/", afilter=None, dirs=True):
"""Get list of all values matching glob pattern."""
passOperations for modifying dictionary structures including deletion and deep merging with configurable behavior.
def delete(obj, glob, separator="/", afilter=None):
"""Delete all elements matching glob pattern."""
pass
def merge(dst, src, separator="/", afilter=None, flags=MergeType.ADDITIVE):
"""Deep merge source into destination dictionary."""
passLow-level utilities for custom path manipulation and advanced use cases, providing direct access to the underlying path walking and matching algorithms.
# From dpath.segments module
def walk(obj, location=()):
"""Walk object yielding (segments, value) pairs."""
pass
def match(segments, glob):
"""Check if segments match glob pattern."""
pass
def view(obj, glob):
"""Create filtered view of object matching glob."""
passConfiguration options and version information, plus deprecated utility functions for backwards compatibility.
# Configuration options
dpath.options.ALLOW_EMPTY_STRING_KEYS = False # Allow empty string keys in paths
# Version information
dpath.version.__version__ # Package version string
# Deprecated util module (use dpath.* directly instead)
import dpath.util # All functions mirror dpath.* with deprecation warnings# Core type aliases
PathSegment = Union[int, str, bytes]
Filter = Callable[[Any], bool]
Glob = Union[str, Sequence[str]]
Path = Union[str, Sequence[PathSegment]]
Hints = Sequence[Tuple[PathSegment, type]]
Creator = Callable[[Union[MutableMapping, List], Path, int, Optional[Hints]], None]
# Special list index class with negative index support
class ListIndex(int):
"""Integer that supports negative index comparison for list operations."""
def __new__(cls, value: int, list_length: int): ...
def __eq__(self, other): ... # Supports negative index comparison
# Merge behavior flags
class MergeType(IntFlag):
ADDITIVE = auto() # Combine lists (default)
REPLACE = auto() # Replace instead of combining
TYPESAFE = auto() # Raise TypeError on type mismatches
# Exceptions
class PathNotFound(Exception):
"""One or more elements of the requested path did not exist in the object"""
pass
class InvalidGlob(Exception):
"""The glob passed is invalid."""
pass
class InvalidKeyName(Exception):
"""This key contains the separator character or another invalid character"""
pass
class FilteredValue(Exception):
"""Unable to return a value, since the filter rejected it"""
pass