Skip to content
Advertisement

Convert nested list to nested dictionary without duplicates and NAN

I’m pretty new to python and would like to ask for your help or idea in converting nested list to dictionary.

Here is a sample data:

JavaScript

the expected output is like this:

JavaScript

I’ve tried following this link but I am having difficulty to implement it. Python: Combine several nested lists into a dictionary

Is there a way to do this? Thank you in advance for helping me.

Advertisement

Answer

This isn’t exactly a ‘nested dictionary’, in the same sense as the linked question: in their version, looking up a key sequence of length k will take O(k) time on average, since they’re using the mapping and lookup functionality of dictionaries. The size of the data structure doesn’t asymptotically affect performance.

In your data structure, looking up the a key of length k will take O(k*L) time, where L is the maximum number of dictionaries on the same level. This is equivalent (performance-wise) to using only nested lists. As you get more data, performance will worsen (albeit not dramatically).

If you really want to keep your current structure, this code will give matching output to yours:

JavaScript

However, if you have a choice, using a similar approach to the linked thread is probably closer to what you’re looking for, and the code is simpler.

For example:

JavaScript

This will give you the following output:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement