我有以下字典,其中keys
是父类,而values
是从它们继承的子类的列表。
{
"Animal":
["Dog"]
,
"Dog":
["Labrador"]
,
"Vehicle":
["PetrolCar",
"DieselCar"]
,
"DieselCar":
["Hyundai"]
,
"PetrolCar":
["Hyundai",
"Ford"]
}
如您所见,某些父类也是另一个父类(深度继承)的子类,即Animal -> Dog -> Labrador
如何格式化该格式,以便输出表示继承级别,如下所示:
{
"Animal": {
"Dog": {
"Labrador": []
}
},
"Vehicle": {
"PetrolCar": {
"Hyundai": [],
"Ford": []
},
"DieselCar": {
"Hyundai": []
}
}
}
我还希望能够通过添加更多的父母或孩子来扩展提供的数据集。例如:将ElectricCar
添加为Vehicle
的子级,并将Tesla
添加为ElectricCar
的子级。并将Cat
添加为Animal
的子代,而没有其子代。
输入:
{
"Animal":
["Dog",
"Cat"]
,
"Dog":
["Labrador"]
,
"Vehicle":
["PetrolCar",
"DieselCar",
"ElectricCar"]
,
"DieselCar":
["Hyundai"]
,
"PetrolCar":
["Hyundai",
"Ford"]
,
"ElectricCar":
["Tesla"]
}
输出:
{
"Animal": {
"Dog": {
"Labrador": []
},
"Cat": []
},
"Vehicle": {
"PetrolCar": {
"Hyundai": [],
"Ford": []
},
"DieselCar": {
"Hyundai": []
},
"ElectricCar": {
"Tesla": []
}
}
}
答案 0 :(得分:4)
您可以使用递归生成嵌套字典,然后删除没有任何子代的键:
data = {'Animal': ['Dog', 'Cat'], 'Dog': ['Labrador'], 'Vehicle': ['PetrolCar', 'DieselCar', 'ElectricCar'], 'DieselCar': ['Hyundai'], 'PetrolCar': ['Hyundai', 'Ford'], 'ElectricCar': ['Tesla']}
def build(key):
return {i:[] if i not in data else build(i) for i in data[key]}
results = {i:build(i) for i in data}
import json
print(json.dumps({a:b for a, b in results.items() if any(h for h in b.values())}, indent=4))
输出:
{
"Animal": {
"Dog": {
"Labrador": []
},
"Cat": []
},
"Vehicle": {
"PetrolCar": {
"Hyundai": [],
"Ford": []
},
"DieselCar": {
"Hyundai": []
},
"ElectricCar": {
"Tesla": []
}
}
}