从平面字典创建嵌套字典

时间:2019-03-24 23:28:57

标签: python python-2.7 dictionary nested

我有以下字典,其中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": []
        }
    }
}

1 个答案:

答案 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": []
     }
   }
}