Skip to content
Advertisement

Creating a nested dictionary from a flattened dictionary

I have a flattened dictionary which I want to make into a nested one, of the form

JavaScript

I want to convert it to the form

JavaScript

The structure of the flat dictionary is such that there should not be any problems with ambiguities. I want it to work for dictionaries of arbitrary depth, but performance is not really an issue. I’ve seen lots of methods for flattening a nested dictionary, but basically none for nesting a flattened dictionary. The values stored in the dictionary are either scalars or strings, never iterables.

So far I have got something which can take the input

JavaScript

to the output

JavaScript

using the code

JavaScript

But I’m having trouble working out how to make this into something which recursively creates all levels of the dictionary.

Any help would be appreciated!

(As for why I want to do this: I have a file whose structure is equivalent to a nested dict, and I want to store this file’s contents in the attributes dictionary of a NetCDF file and retrieve it later. However NetCDF only allows you to put flat dictionaries as the attributes, so I want to unflatten the dictionary I previously stored in the NetCDF file.)

Advertisement

Answer

Here is my take:

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