Reputation: 14112
I have a function which takes a dict and prints it's content in a nice sexy way.
I would like to edit the function to control the depth of the dict but I'm kind of lost.
here is the function:
def print_dict(_dict, indent=""):
for 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)
for i 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 this makes sense.
Upvotes: 0
Views: 134
Reputation: 17761
Change the signature of your function so that it accepts two new parameters: depth
and max_depth
:
def print_dict(_dict, indent="", depth=0, max_depth=-1):
Before each call to 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, at the start of the function, check depth
against max_depth
:
def print_dict(_dict, indent="", depth=0, max_depth=-1):
if max_depth > 0 and depth > max_depth:
return
Upvotes: 2