Flattening Nested Dictionaries
Ever needed to write your own JSON or XML parser? Probably no. There are ready-to-use implementations in almost all programming languages. I also have not think about it till last week. Then, I am asked to implement a method to flatten nested dictionaries. This led me thoughts on possible issues while implementing such parser.
Last week, I am asked to implement a nested dictionary flattener method in an interview I had. Given a sample input-output dictionary pair,
interviewer asked me to implement my solution in language of my choice. I usually implement solutions with C++11 in interviews. I immediately
realized that I would need to deal with
map<string,void*>. Then I changed the editor to Python and exploit the recurrence
The implementation above is made by me assuming it is not allowed to manipulate the input dictionary. Otherwise, I would follow a different strategy for
this problem. I also added simple corner-case checks during interview to pass all test cases. The
flattenDict() directory successfully returns
the same result as below.
In case you wonder why I immediately change to Python from C++11, the reason is the ease of using
isinstance() method instead of dealing dynamic
casting of void pointers in C++. There might be a compiler specific solution in C++ for this problem, I might write on it in the following posts.
Please do not hesitate to provide feedback anytime.
See you on forthcoming posts.