I have created a dictionary like so:
d = {1: {3: {}, 4: {6: {}}}, 5: {}}
Then I iterate through all the items and I can do it recursively:
def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))
pretty(d)
My goal is to store the output into a string variable in such a way that I can manipulate it. Therefore the result should be something like this:
msg ="""
1
3
4
6
5
"""
I tried to reach my goal with the following implementation:
def pretty(d, indent=0, indent_before=0, msg_old=""):
for key, value in d.items():
#print('\t' * indent + str(key) + '({})({})'.format(indent,indent_before))
msg = msg_old+'\t' * indent + str(key) + '({})({})\n'.format(indent,indent_before)
if isinstance(value, dict):
pretty(value, indent+1, indent, msg)
else:
print('\t' * (indent+1) + str(value))
return msg
msg = pretty(result)
print(msg)
But the output of my attempt is: None
Would you be able to suggest a smart and elegant way to achieve the desired result?