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 […]
Categories
How does this recursive Python code work?
- Post author By Full Stack
- Post date August 1, 2020
- No Comments on How does this recursive Python code work?
- Tags _get_new_prefix(prefix, '+447423456789'], 'city': 'london'}, 'phone-numbers': ['+447421234567', 'residence': {'address': {'first-line': 'Alexandra Rd', 'second-line': '', 'separator' => '', 'zip': 'N8 0PP', "Key", { "country": "uk", {'age': 41, }, } 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., dict): return {prefix: data} if prefix else data result = {} for (key, I came across this recursive function that's supposed flatten a dictionary: def flatten(data, prefix, separator): return (separator.join((prefix, separator='.'): """Flattens a nested dict structure. """ if not isinstance(data, separator=separator)) return result def _get_new_prefix(prefix, str(key))) if prefix else str(key)) it's also supposed to be fed with this data: nested = { 'fullname': 'Alessandra', value) in data.items(): result.update(flatten(value