我有一个嵌套字典,如下所示:
d= {"key1":"A", "key2":"B", "score1":0.1, "score2":0.4, "depth":0,
"chain":[
{"key1":"A1", "key2":"B1", "score1":0.2, "score2":0.5, "depth":1,
"chain":[{"key1":"A11", "key2":"B11","score1":0.3, "score2":0.6, "depth":2},
{"key1":"A12", "key2":"B12","score1":0.5, "score2":0.7, "depth":2}]
},
{"key1":"A2", "key2":"B2","score1":0.1, "score2":0.2,"depth":1,
"chain":[{None, None, None, None, None},
{"key1":"A22", "key2":"B22","score1":0.1, "score2":0.5, "depth":2}]
}
]
}
我想创建一个函数,当我调用fun(key1, d)
时,它可以返回一个保留原始层次结构的字典,但在每个级别内,它将返回key1的值,并总结得分1的值和得分2,如下所示:
{"A":0.5, "depth":0,
"chain":[
{"A1":0.7, "depth":1,
"chain":[{"A11":0.9,"depth":2},
{"A12":1.3, "depth":2}]
},
{"A2":0.3,"depth":1,
"chain":[None,
{"A22":0.6, "depth":2}]
}
]
}
我该怎么做? 我试过了
def gen_dict_extract(key, input_dic):
return {input_dic[key]:input_dic["score1"]+input_dic["score2"],
"depth":input_dic["depth"],
"chain": gen_dict_extract(key,input_dic["chain"])}
答案 0 :(得分:1)
您尝试过的解决方案有两个问题:
chain
不保证存在并且chain
是词典列表,您将其视为单个词典希望以下内容可以满足您的要求:
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"] = [gen_dict_extract(key, x) for x in input_dic["chain"]]
return rv
答案 1 :(得分:0)
由于“链”列表中没有“ None”,因此以下功能最终起作用,它根据提供的@dvk解决方案进行了一些细微更新:
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