dpath: Filesystem-like Pathing for Dictionaries
dpath-python provides filesystem-like pathing and searching capabilities for nested dictionary and list structures. It allows you to get, set, delete, and search data within complex Python objects using a simple string path syntax. The current version is 2.2.0, and the library maintains an active release cadence with regular updates and bug fixes.
Warnings
- breaking dpath dropped support for Python 2.x. Any projects relying on older Python versions will need to upgrade to Python 3.7+.
- breaking Behavior for interpreting integer-like path segments when creating new paths was changed to resolve ambiguity. This may lead to dictionary keys being created (e.g., `{'0': ...}`) instead of list indices (e.g., `[..., ...]`) if the target path is not an existing list or explicitly initialized as one.
- gotcha `dpath.values()` and `dpath.search()` return generators, not immediate lists. If you expect a list, you must explicitly convert the generator.
- gotcha The `dpath.merge()` function's default behavior can replace entire lists or dictionaries. For more granular control over merging, especially for lists, the `merge_types` parameter should be used.
Install
-
pip install dpath
Imports
- dpath
import dpath
Quickstart
import dpath
# Sample data
data = {
"user": {
"profile": {
"name": "Alice",
"age": 30,
"interests": ["coding", "photography"]
},
"settings": {
"theme": "dark"
}
},
"items": [
{"id": 1, "name": "itemA"},
{"id": 2, "name": "itemB"}
]
}
print("Original data:")
print(data)
print("-" * 20)
# Get a value
name = dpath.get(data, '/user/profile/name')
print(f"User name: {name}")
# Set a value (creates path if it doesn't exist)
dpath.set(data, '/user/profile/age', 31)
print(f"Updated age: {dpath.get(data, '/user/profile/age')}")
dpath.set(data, '/user/profile/city', 'New York')
print(f"Added city: {dpath.get(data, '/user/profile/city')}")
# Get all values matching a pattern (returns a generator)
print("\nAll item names:")
for item_name in dpath.values(data, '/items/*/name'):
print(f"- {item_name}")
# Merge data (default is to update/replace)
new_settings = {"user": {"settings": {"notifications": True}}}
dpath.merge(data, new_settings)
print("\nData after merge:")
print(data)
# Delete a path
dpath.delete(data, '/user/settings/notifications')
print("\nData after deleting notifications:")
print(data)