Hi @gokulnk,
I ripped up a quick code with a nested function which takes care of any depth. I have tested my code against your inputs and outputs and it seems to be working fine. Check it out and leave me a comment in git if you find any issue.
https://github.com/mightypanda-x/flat-to-nested
I had not upvoted your comment because I was testing your code. I ran some fixed value tests and some random tests. Looks like your code is taking care of all the scenarios :)
Upvoted your answer with 100%. Unless I get a better solution, looks like you are going to be the winner of this Gig.
Glad it worked. I had fun solving it.
good job!