将JSON键:平面结构中的值对转换为键:值树结构

时间:2016-09-16 11:22:59

标签: python json data-structures

可以将相同“级别”(平面结构)中的键:值对数据列表转换为树结构键:该数据的值?

示例:

自:

[{"COD": "20000", "VAL": "Fanerozoico"}, {"COD": "23000", "VAL": "Cenozoico"}, {"COD": "23300", "VAL": "Quaternario"}, {"COD": "23310", "VAL": "Pleistocenico"}, {"COD": "23314", "VAL": "Pleistocenico Superior"}, {"COD": "23200", "VAL": "Neogénico"}, {"COD": "23220", "VAL": "Pliocénico"}, {"COD": "23222", "VAL": "Piacenziano"}]

分为:

{
"Fanerozoico": {
    "COD": "20000",
    "Cenozoico": {
        "COD": "23000",
        "Quaternario": {
            "COD": "23300",
            "Pleistocenico": {
                "COD": "23310",
                "Pleistocenico Superior": {
                    "COD": "23314"
                }
            }
        },
        "Neogenico": {
            "COD": "23200",
            "Pliocenico": {
                "COD": "23220",
                "Piacenziano": {
                    "COD": "23222"
                }
            }
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

我的尝试(有效但可能不是最佳解决方案):

mylist = [
    {"COD": "20000", "VAL": "Fanerozoico"},
    {"COD": "23000", "VAL": "Cenozoico"},
    {"COD": "23300", "VAL": "Quaternario"},
    {"COD": "23310", "VAL": "Pleistocenico"},
    {"COD": "23314", "VAL": "Pleistocenico Superior"},
    {"COD": "23200", "VAL": "Neogénico"},
    {"COD": "23220", "VAL": "Pliocénico"},
    {"COD": "23222", "VAL": "Piacenziano"}
]


COD_LEN = 5

class CODMapper(object):
    def __init__(self, kvlist):
        self._map = {item["COD"]: item["VAL"] for item in kvlist}

    def getchildren(self, key):
        ' return a list of all direct children of a given key '
        if len(key) == COD_LEN:
            return []
        suffix = "0"*(COD_LEN-len(key)-1)
        return [(cod, val) for cod, val in self._map.items()
                        if  cod.startswith(key)
                        and cod.endswith(suffix)
                        and cod[len(key)] != "0"
                ]

    def todict(self, key=""):
        ' Creates the dictionnary structured as you want '
        children = self.getchildren(key)
        result = {}
        for cod, val in children:
            inner_dict = {"COD": cod}
            new_key = cod[:len(key)+1]
            inner_dict.update(self.todict(new_key))
            result[val] = inner_dict
        return result



from pprint import pprint
pprint(CODMapper(mylist).todict())

将输出:

{'Fanerozoico': {'COD': '20000',
    'Cenozoico': {'COD': '23000',
        'Neogénico': {'COD': '23200',
            'Pliocénico': {'COD': '23220',
                'Piacenziano': {'COD': '23222'}}},
        'Quaternario': {'COD': '23300',
            'Pleistocenico': {'COD': '23310',
                'Pleistocenico Superior': {'COD': '23314'}}}}}}