Skip to main content

A tool for iterating dictionaries as trees and printing all leaf nodes at some path

Project description

Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of all leaves at all trajectories dict[A][B][C][D]

If the path is an empty string, returns the original dict

Each non-leaf node can be either a dictionary or list of dictionaries Each leaf node can be an arbitrary object.

import dictsearch

d = dict() d[“A”] = dict() d[“A”][“B”] = [] d[“A”][“B”].append(dict()) d[“A”][“B”][0][“C”] = 123 d[“A”][“B”].append(dict()) d[“A”][“B”][1][“C”] = 123 d[“A”][“B”].append(dict()) d[“A”][“B”][2][“D”] = dict() d[“A”][“B”][2][“D”][“E”] = “ASDF”

print(d) print( dictsearch.iterate_dictionary(d,”X/Y/Z”)) print( dictsearch.iterate_dictionary(d,”A”)) print( dictsearch.iterate_dictionary(d,”A/B”)) print( dictsearch.iterate_dictionary(d,”A/C”)) print( dictsearch.iterate_dictionary(d,”A/B/C”)) print( dictsearch.iterate_dictionary(d,”A/B/C/D”)) #DOES NOT EXIST; D NOT AFTER PATH “C” print( dictsearch.iterate_dictionary(d,”A/B/D/E”)) print( dictsearch.iterate_dictionary(d,”A/B/E”)) #DOES NOT EXIST; E NOT A SUBPATH OF “B”

>>

{‘A’: {‘B’: [{‘C’: 123}, {‘C’: 123}, {‘D’: {‘E’: ‘ASDF’}}]}} [] [{‘B’: [{‘C’: 123}, {‘C’: 123}, {‘D’: {‘E’: ‘ASDF’}}]}] [{‘C’: 123}, {‘C’: 123}, {‘D’: {‘E’: ‘ASDF’}}] [] [123, 123] [] [‘ASDF’] []

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dictsearch-1.1.1.tar.gz (1.3 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page