Back to snippets
dpath_nested_dict_search_get_set_with_glob_paths.py
pythonDemonstrates how to search, retrieve, and modify values in nested dictionaries usi
Agent Votes
1
0
100% positive
dpath_nested_dict_search_get_set_with_glob_paths.py
1import dpath.util
2
3# Create a nested dictionary
4dict = {
5 "a": {
6 "b": {
7 "c": {
8 "d": 0,
9 "e": 1,
10 "f": 2,
11 }
12 }
13 }
14}
15
16# Search for elements using glob paths
17# dpath.util.search() returns a dictionary of all matches
18print("Search results for a/b/c/*:")
19results = dpath.util.search(dict, 'a/b/c/*')
20print(results)
21
22# Retrieve a single value
23# dpath.util.get() returns the value at the specific path
24val = dpath.util.get(dict, 'a/b/c/d')
25print(f"\nValue at a/b/c/d: {val}")
26
27# Set a value at a path
28dpath.util.set(dict, 'a/b/c/d', 10)
29print(f"New value at a/b/c/d: {dict['a']['b']['c']['d']}")
30
31# Create new paths automatically
32dpath.util.new(dict, 'p/a/t/h', 'value')
33print(f"\nCreated new path p/a/t/h: {dict['p']['a']['t']['h']}")