题干:
有若干种不同的树形结构, 需要映射为扁平化的dict, 为了不进行硬编码, 需将树形结构转换为扁平化结构, 请实现该程序
如输入:
in_data = {
'jack': {
'math': {'teacher': 'zhang', 'score': '75'},
'english': {'teacher': 'xu', 'score': '90'},
'height': '172'
}
}
则输出:
{
'jack_math_teacher': 'zhang',
'jack_math_score': '75',
'jack_english_teacher': 'xu',
'jack_english_score': '90',
'jack_height': '172'
}
解答如下:
a_dict = {}
for i, iv in in_data.items():
for j, jv in in_data[i].items():
if isinstance(jv, dict):
for x, xv in in_data[i][j].items():
temp = i + "_" + j + "_" + x
# print(temp)
a_dict[temp] = xv
else:
temp = i + "_" + j
# print(temp)
a_dict[temp] = jv
print(a_dict)