2

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?

1
  • 1
    Please explain in detail what "without success" means, how your function was supposed to work, and at what point it first went wrong. Commented Sep 3, 2020 at 18:12

3 Answers 3

2

The main problem is that in your recursive call you are discarding the return value (i.e. calling pretty but not appending the return value to the existing message).

Here is a solution based closely on your original code.

d = {1: {3: {}, 4: {6: {}}}, 5: {}}

def pretty(d, indent=0):
    msg = ''
    for key, value in d.items():
        msg += '\t' * indent + str(key) + '\n'
        if isinstance(value, dict):
            msg += pretty(value, indent+1)  # <=== see how return value is used
        else:
            msg += '\t' * (indent+1) + str(value) + '\n'
    return msg

print(pretty(d))
Sign up to request clarification or add additional context in comments.

Comments

0

I know you are trying to implement your own solution but you never mentioned the builtin pprint library/function that does this all for you:

from pprint import pformat
d = {1: {3: {}, 4: {6: {}}}, 5: {}}
print(pformat(d, indent=0))

{1: {3: {}, 4: {6: {}}}, 5: {}}

1 Comment

OP wants a string returned, so you probably want pprint.pformat rather than pprint.pprint.
0

If your dict is well-formed, then you can use:

>>> def pretty(d, indent=0):
...     return "".join(["\n" + "\t" * indent + str(k) +
...                     pretty(v, indent + 1) for k, v in d.items()])
...
>>> d = {1: {3: {}, 4: {6: {}}}, 5: {}}
>>> pretty(d)
'\n1\n\t3\n\t4\n\t\t6\n5'
>>> print(pretty(d))

1
        3
        4
                6
5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.