我正在尝试传入一个函数,这个字符串将被解释为确定更新字典所需的字典调用。
这是我到目前为止的一个例子,硬编码:
import json
from collections import defaultdict
def default_dict():
return defaultdict(default_dict)
def build_dict():
d["a"]["b"]["c"]["d"]["e"]["f"].update({})
d["a"]["b"]["c1"]["d1"].update({})
return json.dumps(d)
d = default_dict()
print build_dict()
但是为了对我有用,我想将字符串传递给build_dict()函数。让我们称之为'
:for s in ["a/b/c/d/e/f", "a/b/c1/d1"]:
print build_dict(s)
哪个应打印以下内容(与我硬编码的示例中的内容完全相同:
{
"a": {
"b": {
"c": {
"d": {
"e": {
"f": {}
}
}
},
"c1": {
"d1": {}
}
}
}
}
在我的硬编码示例中,我必须确保支持多个分支(就我测试而言)。
我目前正在尝试的内容:
答案 0 :(得分:1)
I worked out a solution to my own question.
import json
import dpath.util
def build_dict(viewsDict, viewsList):
for views in viewsList:
viewsDict = new_keys(viewsDict, views)
return viewsDict
def new_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)
答案 1 :(得分:0)
这会根据路径序列构建一个dict并传递你的测试用例。
它从上到下构建一个字典,如果缺少新的密钥则添加它们,并在它们存在时更新现有的字典。
def build_dict(string_seq):
d = {}
for s in string_seq:
active_d = d
parts = s.split("/")
for p in parts:
if p not in active_d:
active_d[p] = {}
active_d = active_d[p]
return d
expected = {
"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)
assert result == expected