Transform JSON key:value pairs in flat structure into key:value tree structure
<p>It is possible to transform list of key:value pairs of data in the same "level" (flat structure) into a tree structure key:value of that data?</p>

<p>Example:</p>

<p>From:</p>

<pre><code>[{"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"}]
</code></pre>

<p>Into:</p>

<pre><code>{
"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"
                }
            }
        }
    }
}
}
</code></pre>

<p>My attempt (that works but might not be the best solution):</p>

<pre><code>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())
</code></pre>

<p>Will output:</p>

<pre><code>{'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'}}}}}}
</code></pre>

python json data-structures