Skip to content Skip to sidebar Skip to footer

How To Interpret A String To Define A Dictionary Call?

I am attempting to pass in to a function, a string which will be interpreted to determine the desired dictionary call required to update a dictionary. Here is an example of what I

Solution 1:

I worked out a solution to my own question.

import json
import dpath.util

defbuild_dict(viewsDict, viewsList):
    for views in viewsList:
        viewsDict = new_keys(viewsDict, views)
    return viewsDict

defnew_keys(viewsDict, views):
    dpath.util.new(viewsDict, views, {})
    return viewsDict

viewsDict = {}
viewsList = [
    "a/b/c/d/e/f",
    "a/b/c1/d1"
]

print json.dumps(build_dict(viewsDict, viewsList), indent=4, sort_keys=True)

Solution 2:

This builds a dict based on sequence of paths and passes your test case.

It builds a dictionary from up to down, adding a new keys if they are missing, and updating an existing dictionary when they are present.

def build_dict(string_seq):
    d = {}
    for s in string_seq:
        active_d = dparts= s.split("/")
        for p in parts:
            if p not in active_d:
                active_d[p] = {}
            active_d = active_d[p]
    returndexpected= {
    "a": {
        "b": {
            "c": {
                "d": {
                    "e": {
                        "f": {}
                    }
                }
            },
            "c1": {
                "d1": {}
            }
        }
    }
}

string_seq = ["a/b/c/d/e/f", "a/b/c1/d1"]
result = build_dict(string_seq)
assertresult== expected

Post a Comment for "How To Interpret A String To Define A Dictionary Call?"