Reputation: 129
I have the following dictionary in which keys
are parent classes and values
are a list of child classes which inherit from them.
{
"Animal":
["Dog"]
,
"Dog":
["Labrador"]
,
"Vehicle":
["PetrolCar",
"DieselCar"]
,
"DieselCar":
["Hyundai"]
,
"PetrolCar":
["Hyundai",
"Ford"]
}
As you can see, some of the parent classes are also children of another parent class (deep inheritance), i.e. Animal -> Dog -> Labrador
How can I format this so that the output represents the levels of inheritance, something like this:
{
"Animal": {
"Dog": {
"Labrador": []
}
},
"Vehicle": {
"PetrolCar": {
"Hyundai": [],
"Ford": []
},
"DieselCar": {
"Hyundai": []
}
}
}
I also want to be able to extend the provided dataset by adding more parents or children. For example: Adding ElectricCar
as a child of Vehicle
and Tesla
as a child of ElectricCar
. And adding Cat
as a child of Animal
, with no children of it's own.
Input:
{
"Animal":
["Dog",
"Cat"]
,
"Dog":
["Labrador"]
,
"Vehicle":
["PetrolCar",
"DieselCar",
"ElectricCar"]
,
"DieselCar":
["Hyundai"]
,
"PetrolCar":
["Hyundai",
"Ford"]
,
"ElectricCar":
["Tesla"]
}
Output:
{
"Animal": {
"Dog": {
"Labrador": []
},
"Cat": []
},
"Vehicle": {
"PetrolCar": {
"Hyundai": [],
"Ford": []
},
"DieselCar": {
"Hyundai": []
},
"ElectricCar": {
"Tesla": []
}
}
}
Upvotes: 3
Views: 220
Reputation: 71451
You can use recursion to produce the nested dictionary, and then remove keys that do not have any children:
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))
Output:
{
"Animal": {
"Dog": {
"Labrador": []
},
"Cat": []
},
"Vehicle": {
"PetrolCar": {
"Hyundai": [],
"Ford": []
},
"DieselCar": {
"Hyundai": []
},
"ElectricCar": {
"Tesla": []
}
}
}
Upvotes: 5