Print a specific subset of keys in a dictionary

I have a dictionary in Python where keys are paths. For instance:

dict["/A"] = 0
dict["/A/B"] = 1
dict["/A/C"] = 1

dict["/X"] = 10
dict["/X/Y"] = 11

I was wondering what a good way to print all the “subpaths” using any key.

For example, for a function called "print_dict_path" that does this, something like

print_dict_path("/A")

or

print_dict_path("/A/B")

will output something like:

"B" = 1
"C" = 1

The only method I can think of is something like using a regular expression and going through the entire dictionary, but I'm not sure if this is the best method (and I am not good at regular expression).

Thanks for any help.

+5
source share
5 answers

One possibility without using regex is just to use startswith

top_path = '/A/B'
for p in d.iterkeys():
    if p.startswith(top_path):
        print d[p]
+5

str.find:

def print_dict_path(prefix, d):
    for k in d:
        if k.find(prefix) == 0:
            print "\"{0}\" = {1}".format(k,d[k])
+1

, dict.

def filter_dict_path( d, sub ):
    for key, val in d.iteritems():
        if key.startswith(sub): ## or do you want `sub in key` ?
            yield key, val

print dict(filter_dict_path( old_dict, sub ))

, : .

+1

​​ ? , :

{
    "A": {
        "value": 0
        "dirs": {
            "B": {
                "value": 1
            }
            "C": {
                "value": 1
            }
        }
    "X": {
        "value": 10
        "dirs": {
            "Y": {
                "value": 11
            }
}

- , Python .

+1

, for

top_path = '/A/B'
for p in (p for p in d.iterkeys() if p.startswith(top_path)):
    print d[p]

, , trie

+1

All Articles