简体   繁体   中英

How does this recursive Python code work?

I came across this recursive function that's supposed flatten a dictionary:

def flatten(data, prefix='', separator='.'):
    """Flattens a nested dict structure. """
    if not isinstance(data, dict):
        return {prefix: data} if prefix else data

        result = {}
        for (key, value) in data.items():
            result.update(flatten(value,_get_new_prefix(prefix, key, separator),
            separator=separator))
        return result

def _get_new_prefix(prefix, key, separator):
    return (separator.join((prefix, str(key))) if prefix else str(key))

it's also supposed to be fed with this data:

nested = {
 'fullname': 'Alessandra',
 'age': 41,
 'phone-numbers': ['+447421234567', '+447423456789'],
 'residence': {'address': {'first-line': 'Alexandra Rd','second-line': '',},
 'zip': 'N8 0PP',
 'city': 'London',
 'country': 'UK',
 },
}

I'm trying to figure out how it works and particularly how the "prefix" parameter works and in what case it will not be empty.

The flatten() function builds the path down the tree, where the names in the path are separated by the separator. The prefix is added to the beginning of that path.

prefix is only "empty" if you set it to None . That will have the effect of suppressing the prefix.

For example, compare the output of this:

[print(k, ' = ', v) for k,v in flatten(nested, prefix='xxx', separator='/').items()]

...with this:

[print(k, ' = ', v) for k,v in flatten(nested, prefix=None).items()]

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