Faced the problem of searching in the "deep" dictionary (many dictionaries nested in each other). The dictionary is obtained from the .json file and contains nested dictionaries of a similar structure. My task is to get all the values ​​of certain fields of dictionaries on one of the lower levels, now I do recursively, but maybe someone has encountered a similar problem, and there are some modules like beautifulsoup for solving such problems.

1 answer 1

I liked the dpath module for working with dictionaries:

# pip install dpath import dpath.util x = { "a": { "b": { "3": 2, "43": 30, "c": [], "d": ['red', 'buggy', 'bumpers'], } } } 

Getting the value:

 print(dpath.util.get(x, 'a/b/d')) # ['red', 'buggy', 'bumpers'] print(dpath.util.get(x, 'a/b/d/0')) # red print(dpath.util.get(x, 'a/b/d/1')) # buggy print(dpath.util.get(x, 'a/b/43')) # 30 print() 

Getting a list of values:

 print(dpath.util.values(x, "**/43")) # [30] print(dpath.util.values(x, "**/d/1")) # [buggy] print() 

Search:

 print(dpath.util.search(x, "**/43")) # {'a': {'b': {'43': 30}}} print(list(dpath.util.search(x, "**/43", yielded=True))) # [('a/b/43', 30)] print() 

Search with filtering:

 def afilter(x): return str(x).isdecimal() result = dpath.util.search(x, '**', afilter=afilter) print(result) # {'a': {'b': {'3': 2, '43': 30}}} # Фильтрация через лябмды: result = dpath.util.search(x, '**', afilter=lambda x: str(x).isdecimal()) print(result) # {'a': {'b': {'3': 2, '43': 30}}} result = list(dpath.util.search(x, '**', yielded=True, afilter=afilter)) print(result) # [('a/b/3', 2), ('a/b/43', 30)] 

Code from the example

  • Thank you very much for your reply. - Denis Stepanov