Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a particular subset of keys in a dictionary

I have a dictionary in Python where the keys are pathnames. For example:

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

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

I was wondering, what's a good way to print all "subpaths" given any key.

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

print_dict_path("/A")

or

print_dict_path("/A/B")

would print out something like:

"B" = 1
"C" = 1

The only method I can think of is something like using regex and going through the entire dictionary, but I'm not sure if that's the best method (nor am I that well versed in regex).

Thanks for any help.

like image 300
julian Avatar asked Aug 09 '10 14:08

julian


2 Answers

One possibility without using regex is to just use startswith

top_path = '/A/B'
for p in d.iterkeys():
    if p.startswith(top_path):
        print d[p]
like image 189
Rakis Avatar answered Nov 05 '22 11:11

Rakis


You can use str.find:

def print_dict_path(prefix, d):
    for k in d:
        if k.find(prefix) == 0:
            print "\"{0}\" = {1}".format(k,d[k])
like image 37
GWW Avatar answered Nov 05 '22 13:11

GWW