Question: A nested dictionary is a dictionary that contains dictionaries as values. A common practice to work with nested dictionaries is to flatten them, so that
A nested dictionary is a dictionary that contains dictionaries as values. A common practice to work with nested dictionaries is to flatten them, so that the key-value pairs in the children (inner) dictionaries are moved to the parent (outer) dictionary.
Write a recursive function that flattens a nested dictionary (nested_dict). In the final flattened dictionary, the key of a value should be a concatenation of all keys you would use to trace down to that value in the original nested dictionary. You can read the example and doctests below for more details.
You can assume that all keys are string type, and values can be of any type. Whenever a value is a dictionary, you need to flatten it. You can assume that the dictionaries (both outer and inner) will not be empty.
You can also assume that all keys in the nested_dict will not form duplicate concatenations. For example, if nested_dict["A"]["D"]["E"] exists, you can assume nested_dict["A"]["DE"] or nested_dict["ADE"] will not exist, since their concatenations are all "ADE".
You cannot use map() and filter(). However, you can use loops to process dictionaries. You cannot use a recursive helper function, including an inner function.
example:
>>> flatten_dict({'A': 1, 'B': 2})
{'A': 1, 'B': 2}
>>> flatten_dict({'Hi': True, 'Hello': {'World': 'Java', 'Kitty': 'Python'}})
{'Hi': True, 'HelloWorld': 'Java', 'HelloKitty': 'Python'}
>>> flatten_dict({'A': {'B': 1, 'C': 2, 'D': {'E': 3, 'F': 4}}, 'G': 5, 'H': 6})
{'AB': 1, 'AC': 2, 'ADE': 3, 'ADF': 4, 'G': 5, 'H': 6}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
