![]() |
VOOZH | about |
We are given a nested dictionary we need to flatten the dictionary into single dictionary. For example, we are given a nested dictionary a = {'a': 1, 'b': {'x': 2, 'y': {'z': 3}}, 'c': {'m': 4} } we need to flatten the dictionary so that output becomes {'a': 1, 'c_m': 4, 'b_x': 2, 'b_y_z': 3}. We can use stack and queues for flattening it.
Using a stack, we push tuples of the current dictionary and its parent key, then pop them to flatten nested dictionaries by concatenating keys. If a value is a dictionary then it's pushed back onto the stack for further processing.
{'a': 1, 'c_m': 4, 'b_x': 2, 'b_y_z': 3}
Explanation:
Using a queue, we enqueue tuples of the current dictionary and its parent key, then dequeue them to process the dictionary and flatten it. If a value is a nested dictionary, it's enqueued for further processing.
{'a': 1, 'b_x': 2, 'c_m': 4, 'b_y_z': 3}
Explanation: