我有一个嵌套字典,如下所示:
d = {'chain': [{'chain': [{'chain': [None, None, None, None, None],
'depth': 2,
'key1': 'A11',
'key2': 'B11',
'score1': 0.3,
'score2': 0.6},
{'chain': [{'chain': [None, None, None, None, None],
'depth': 3,
'key1': 'A121',
'key2': 'B121',
'score1': 0.2,
'score2': 0.6}],
'depth': 2,
'key1': 'A12',
'key2': 'B12',
'score1': 0.5,
'score2': 0.7}],
'depth': 1,
'key1': 'A1',
'key2': 'B1',
'score1': 0.2,
'score2': 0.5},
{'chain': [{'chain': [None, None, None, None, None],
'depth': 2,
'key1': 'A22',
'key2': 'B22',
'score1': 0.1,
'score2': 0.5}],
'depth': 1,
'key1': 'A2',
'key2': 'B2',
'score1': 0.1,
'score2': 0.2}],
'depth': 0,
'key1': 'A',
'key2': 'B',
'score1': 0.1,
'score2': 0.4}
我想创建一个函数,当我调用fun(key1, d)
时,它可以返回一个保持原始层次结构的字典,但在每个级别中,它将:
结果如下:
{"A":0.5, "depth":0, "chain":[
{"A1":0.7, "depth":1,"chain":[
{"A11":0.9,"depth":2,"key2":"B11", "chain":[]},
{"A12":1.3, "depth":2,"chain":[
{"A121":0.8, "depth":3, "key2":"B121", "chain":[]}
]}]},
{"A2":0.3,"depth":1,"chain":[
{"A22":0.6, "depth":2, "key2":"B22","chain":[]}
]}]
}
我使用以下方法实现了1和2:
def gen_dict_extract(key, input_dic):
rv = {
input_dic[key]: input_dic["score1"] + input_dic["score2"],
"depth": input_dic["depth"],
}
if "chain" in input_dic:
rv["chain"]=[]
for x in input_dic["chain"]:
if x is not None:
rv["chain"].insert(input_dic["chain"].index(x),gen_dict_extract(key, x))
return rv
但是我怎么能加3呢?你知道吗
试试这个:
它打印:
相关问题 更多 >
编程相关推荐