Categories
Mastering Development

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.

Leave a Reply

Your email address will not be published. Required fields are marked *