dpath: Filesystem-like Pathing for Dictionaries

2.2.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This example demonstrates how to use `dpath.get`, `dpath.set`, `dpath.values`, `dpath.merge`, and `dpath.delete` to manipulate a nested dictionary and list structure. It shows getting a value, setting/creating new paths, iterating through matching values with wildcards, merging dictionaries, and deleting paths.

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)

view raw JSON →