简体   繁体   中英

How to store the output of a recursive function in Python?

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?

The main problem is that in your recursive call you are discarding the return value (ie 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))

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: {}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM