dictionary - python ordereddict: access certain depth within dict -


i have function takes dict , prints it's content in nice sexy way.

i edit function control depth of dict i'm kind of lost.

here function:

def print_dict(_dict, indent=""):     k, v in _dict.items():         if hasattr(v, 'items'):             print "%s(%s::" % (indent, k)             print_dict(v, indent + "  ")             print "%s)" % indent         elif isinstance(v, list):             print "%s(%s::" % (indent, k)             in v:                 print_dict(dict(i), indent + "  ")             print "%s)" % indent        else:             print "%s(%s::%s)" % (indent, k, v) 

output:

(axis::   (@name::kfcq1[{kfcq1_1}].kfcq1_grid)   (@mdmname::kfcq1[{kfcq1_1}].kfcq1_grid)   (@usemetadatadefinition::true)   (@label::kfcq1_1. veuillez sélectionner votre réponse)   (labels::     (label::       (@language::fra)       (@text::kfcq1_1. veuillez sélectionner votre réponse?)     )   )   (elements::     (element::       (style::none)       (@name::unweightedbase)       (@mdmname::)       (@ishiddenwhencolumn::true)       (labels::         (label::           (@language::fra)           (@text::base brute)         )       )     )    ) 

desired output

print_dict(_dict, depth=0, indent="") (axis::   (@name::kfcq1[{kfcq1_1}].kfcq1_grid)   (@mdmname::kfcq1[{kfcq1_1}].kfcq1_grid)   (@usemetadatadefinition::true)   (@label::kfcq1_1. veuillez sélectionner votre réponse) ) 

really hope makes sense.

change signature of function accepts 2 new parameters: depth , max_depth:

def print_dict(_dict, indent="", depth=0, max_depth=-1): 

before each call print_dict, increment depth:

print_dict(v, indent + "  ", depth=depth + 1, max_depth=max_depth) print_dict(dict(i), indent + "  ", depth=depth + 1, max_depth=max_depth) 

finally, @ start of function, check depth against max_depth:

def print_dict(_dict, indent="", depth=0, max_depth=-1):     if max_depth > 0 , depth > max_depth:         return 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -