我有一条路。使用 dpath-utils,我通过根据路径长度创建子键来创建字典。但在当前示例中,我的路径长度很短,如下所示。
注意: 如果路径很长:“/cbghb6b2861f919f6ffc238a0c5cffed63436/bbc238a0c5cffed6343fc238a0c5cffed63436”。我解释了这一点,因为这就是我使用 dpath.utils 的原因
我使用 dpath.utils 将路径添加到字典的相应键,如下所示。
model_dict = {}
path = "/b6b2861f919f6fc238a0c5cffed63436"
data= {
'metadata': {
'author': None,
'column_name': [...],
'date': datetime.datetime(20...1, 870998),
'metrics': {...},
'name': None, 'source_code_version': None},
'model': <src.python.ml.optis...10f4695f8>
}
}
dpath.util.set(model_dict, path, data)
model_dict = {
'b6b2861f919f6fc238a0c5cffed63436':{
'metadata': {
'author': None,
'column_name': [...],
'date': datetime.datetime(20...1, 870998),
'metrics': {...},
'name': None, 'source_code_version': None},
'model': <src.python.ml.optis...10f4695f8>
}
}
dpath.util.get(model_dict, path)
但是使用路径调用时出现此错误。
输出:
File "/Users/****/Documents/**/src/python/ws/***/restful/**/**.py", line 30, in get_model
return dpath.util.get(self.persisted_file , path)
File "/Users/*****/.virtualenvs/*****/lib/python3.7/site-packages/dpath/util.py", line 171, in get
results = dpath.segments.fold(obj, f, [])
File "/Users/****/.virtualenvs/******/lib/python3.7/site-packages/dpath/segments.py", line 349, in fold
for pair in walk(obj):
File "/Users/******/.virtualenvs/*******/lib/python3.7/site-packages/dpath/segments.py", line 62, in walk
for found in walk(v, location + (k,)):
File "/Users/*****/.virtualenvs/*******/lib/python3.7/site-packages/dpath/segments.py", line 62, in walk
for found in walk(v, location + (k,)):
File "/Users/******/.virtualenvs/********/lib/python3.7/site-packages/dpath/segments.py", line 48, in walk
for k, v in kvs(obj):
File "/Users/*****/.virtualenvs/****/lib/python3.7/site-packages/dpath/segments.py", line 16, in kvs
return zip(range(len(node)), node)
TypeError: object of type 'RegressionModel' has no len()
但是当我直接打电话时,没有问题,但我不想直接打电话。因为我可能想在其子键之一中获取值。以及这有多低。
model_dict.get("b6b2861f919f6fc238a0c5cffed63436")
输出:
{
'metadata': {
'author': None,
'column_name': [...],
'date': datetime.datetime(20...1, 870998),
'metrics': {...},
'name': None, 'source_code_version': None},
'model': <src.python.ml.optis...10f4695f8>
}
}