Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert period delimited string into nested dictionary

I’m trying to convert a string delimited by periods like this fruits.apple.color into a nested dictionary ( later I’ll convert it to JSON):

{
 "fruits": {
     "apple": {
       "color": ''
      }
  }
}

I’m trying to use recursion:

import json

test = "fruits.apple.color";
convertedDict = dict();

def stringToJson(dictionary, keys):
    if "." in keys:
        key, rest = keys.split(".",1);
        print (key, rest);
        if key not in dictionary:
            dictionary[key] = {}
            print (dictionary);
        stringToJson(dictionary[key], rest)
    else:
        dictionary[keys] = ''
        print('dictionary: ', dictionary);

        
convertedDict = stringToJson({}, test);
print(convertedDict);

but I’m getting this output :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fruits apple.color
{'fruits': {}}
apple color
{'apple': {}}
dictionary:  {'color': ''}
None

>Solution :

I will answer with some simple code here, but I advance you might be interested to use extradict.NestedData in the extradict. Just pip install extradict and it should work out of the box: https://github.com/jsbueno/extradict (disclaimer: I am the package author)

Now, looking at your code: it is working nicely
It is jsut that instead of looking at the final result of processing your dictionary, you are looking only at the prints of the intermediate steps: you print a subdictionary when your function is called recursively, and you are not returning the transformed dictionary and looking at that.

The code works because it operates on the parent dictionary, adding the nested keys/dicts in place to it, so, if you just inspect the final state of your parent dicionary you will see the result:

import json

test = "fruits.apple.color";
convertedDict = dict();

def stringToJson(dictionary, keys):
    if "." in keys:
        key, rest = keys.split(".",1);
        print (key, rest);
        if key not in dictionary:
            dictionary[key] = {}
            print (dictionary);
        stringToJson(dictionary[key], rest)
    else:
        dictionary[keys] = ''
        print('dictionary: ', dictionary)
    return dictionary

        
convertedDict = stringToJson({}, test)
print(convertedDict);

I just add the "return" line there: otherwise the function would work and return "None". The dictionary you want was being created, but it is not bound to any variable outside the function, as it was created in the function call itself at stringToJson({}, test).

Instead of adding the return, this will also work: the function call will modify a dictionary to which you have access after it returns. Just change the last script lines to:

convertedDict = {}
stringToJson(convertedDict, test)
print(convertedDict)

Now, back to the begining: while I encourage you to keep fiddling with this code so you get more solid bases with Python and programming in general, if you are using this for production code, just use an external lib, as the extradict I mentioned earlier.
It can handle a lot of corner cases that can be subtle to get right.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading